Skip to content Skip to sidebar Skip to footer

Are Python Tuples Modifiable?

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 wil

Solution 1:

Python tuples are immutable. From the documentation:

Tuples, like strings, are immutable: it is not possible to assign to the individual items of a tuple (you can simulate much of the same effect with slicing and concatenation, though). It is also possible to create tuples which contain mutable objects, such as lists.

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:

data = ["id", "gender", -1]

Solution 2:

That's correct, tuples are immutable. However, you can put any different types into a python list.

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

Solution 3:

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

Solution 4:

From your code, it looks like the first field "id" will never be missing. Let's assume you really want a tuple for passing to your User class.

You could do your checks first and then assign the totality of the result 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]

You should however be careful that the fields (if they exist) that follow are split correctly, otherwise field meaning will get mixed up.

Post a Comment for "Are Python Tuples Modifiable?"