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[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 that you cannot directly assign tuples (for example data[1] = "missing"

), so how is that supposed to be assigned in a pythonic manner?

+3


source to share


4 answers


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]

      

+4


source


That's right, tuples are immutable. However, you can put any types in the python list.



>>> a = []
>>> a.append("a")
>>> a.append(1)
>>> a.append(False)
>>> print a
['a', 1, False]

      

+4


source


If you must use a tuple (although, as others have said, a list should work fine), just store your data in temp variables and create a tuple from scratch with temps at the end of the loop, not at the beginning with dummy values.

0


source


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[1] in "mf":
    data=tuple(words[i] for i in range(0,3))
else:
    data=words[0],"missing",words[2]

      

However, you must be careful that the fields (if they exist) are split correctly, otherwise the field value will be mixed up.

0


source







All Articles