Are python tuples modified?
I am reading and parsing some data. Basically the data is a bunch of integers and strings, so I can't just use a list to store the data. There you are given the number of elements that will be in each dataset, but sometimes some of them are missing. Here's 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 = words[index] index += 1 if words[index] == "m" or words[index] == "f": data = words[index] index += 1 else: data = "missing" if words[index].isdigit(): data = words[index] index += 1 users.append(User(data))
The problem is that you cannot directly assign tuples (for example
data = "missing"
), so how is that supposed to be assigned in a pythonic manner?
Python roots are immutable. From the doc:
Tuples such as strings are immutable: it is not possible to assign individual elements to a tuple (although you can mimic most of the slicing and concatenation effect). It is also possible to create tuples that contain mutable objects such as lists.
This is the main thing that distinguishes them from lists. This works well for one possible solution: use a list instead of a tuple:
data = ["id", "gender", -1]
source to share
From your code, it looks like the first "id" field will never be missing. Let's say you really want a tuple to navigate to your User class.
You can do your checks first, and then assign the entire set of results to your tuple ...
if words in "mf": data=tuple(words[i] for i in range(0,3)) else: data=words,"missing",words
However, you must be careful that the fields (if they exist) are split correctly, otherwise the field value will be mixed up.
source to share