 # Storing variables in tuples?

I just learned about tuples and how they differ from lists (tuples are immutable, where are lists are not) and I was curious as to whether or not you are able to store variables inside tuples. If so, are you able to change the value of the variable contained inside the tuple after defining the tuple? Thanks!

variables are not values, you can’t store them, just like how you can’t store a loop

if what you want from a variable is its ability to change, then you could use a mutable value instead

3 Likes

You can do something like this but like ionatan said the key is the wording of your question, you’d be changing values not variable.

``````a = 2
b = 'hi'
tupleex = (a, b)
print(tupleex)
#prints (2, 'hi')
`````` 1 Like

No. When the tuple is generated the values are used, not the variables. If we change the value it will have no effect on the tuple.

``````>>> a = 1
>>> b = 2
>>> c = (a, b)
>>> c
(1, 2)
>>> a = 3
>>> c
(1, 2)
>>>
``````
4 Likes

As per @ionatan’s comment you can use mutable objects such as lists inside a tuple. For example,

``````this_tuple = (0, 1, [3, 4], 5)
print(this_tuple)
Out: (0, 1, [3, 4], 5)

this_tuple = 'egg'
print(this_tuple)
Out: (0, 1, ['egg', 4], 5)
``````

What you can’t change is the references the tuple holds.
`this_tuple = ['new', 'list', 'object']` for example will throw an error.

1 Like

Thanks for the help everyone, much appreciated!

Something of note, here, is that lists are mutable, even when contained in a tuple.

``````>>> t = (0, 1, ['egg', 4], 5)
>>> t
(0, 1, ['egg', 4], 5)
>>> t = 'bacon'
>>> t
(0, 1, ['egg', 'bacon'], 5)
>>>
``````
2 Likes