Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are python tuples modifiable?

Tags:

python

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?


1 Answers

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]
like image 82
David Heffernan Avatar answered Sep 24 '26 02:09

David Heffernan