-2

I'm trying to understand why my snippet of code ends up with the class "list" as opposed to a Tuple.

The way I'd like it to work is to open a CSV, check for the user/password header and use those to append to a tuple so that I can retrieve accounts by doing accounts[1], accounts[2]

It's important that the list of accounts is immutable to me, so I'm trying to end up with the class tuple.

# our csv file name
filename = "resources/accounts.csv"
with open(filename) as infile:
    reader = csv.DictReader(infile)
    accounts = []
    for row in reader:
        accounts.append((row['user'],row['password']))

print(type(accounts))
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Marcel Doe
  • 57
  • 7

2 Answers2

3
accounts = []
for row in reader:
    accounts.append((row['user'],row['password']))

You're starting with an empty list [] and appending items to it, so you end up with a list. If you want a tuple you could convert the list to one at the end:

accounts = []
for row in reader:
    accounts.append((row['user'],row['password']))
accounts = tuple(accounts)

Better yet, use a generator expression to create a tuple from the get go. That way you avoid creating a temporary list just to throw it away.

with open(filename) as infile:
    reader = csv.DictReader(infile)
    accounts = tuple((row['user'], row['password']) for row in reader)
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
0

As you already know a tuple is immutable. So you are correct in making accounts a list. If you want to store it as a tuple afterwards you can convert it like this:

accounts = tuple(accounts)
Robert Kearns
  • 1,631
  • 1
  • 8
  • 15