I’m reading in and parsing some data. Basically, the data is a bunch of integers and strings, so I can’t use just a list to store the data. There’s a set number of items that will be in each set of data, but sometimes some are missing. Here is what I have.
users = [] # list of objects I'll be creating
# this all gets looped. snipped for brevity
data = "id", "gender", -1 # my main tuple that I will create my object with
words = line.split()
index = 0
data[0] = words[index]
index += 1
if words[index] == "m" or words[index] == "f":
data[1] = words[index]
index += 1
else:
data[1] = "missing"
if words[index].isdigit():
data[2] = words[index]
index += 1
users.append(User(data))
The problem is you can’t seem to be able to assign directly to tuples (such as data[1] = "missing"), so how should this be assigned in a pythonic manner?
Python tuples are immutable. From the documentation:
That’s the principal thing that sets them apart from lists. Which leads nicely on to one possible solution: use a list in place of the tuple: