python: multiple variables using tuple

The way you used the tuple was only to assign the single values to single variables in one line. This doesn't store the tuple anywhere, so you'll be left with 4 variables with 4 different values. When you change the value of country, you change the value of this single variable, not of the tuple, as string variables are "call by value" in python.

If you want to store a tuple you'd do it this way:

tup = ('Diana',32,'Canada','CompSci')

Then you can access the values via the index:

print tup[1] #32

Edit: What I forgot to mention was that tuples are not mutable, so you can access the values, but you can't set them like you could with arrays. You can still do :

name, age, country, job = tup

But the values will be copies of the tuple - so changing these wont change the tuple.


You are just changing the value of the variable Country not the tuple. you can test it this way:

 tup=('Diana',32,'Canada','CompSci')
 name,age,country,career = tup
 print(country)
 country = 'India'
 print(tup)

The output should be as follows:

 Canada
 ('Diana', 32, 'Canada', 'CompSci')

you can't change the value of an element inside a tuple they are immutable. its one the key features of tuples. Lists on the other hand are mutable.


The following snippet code might be helpful to understand the reason. Here, name, age, country and career are single variables and therefore can be modified.

t = (name, age, country, career) = ('Diana',32,'Canada','CompSci')

print(t)            # ('Diana', 32, 'Canada', 'CompSci')
print(country)      # Canada

country = 'India'

print(t)            # ('Diana', 32, 'Canada', 'CompSci')
print(country)      # India

t[2] = 'India'
# The error occurs as expected
TypeError: 'tuple' object does not support item assignment

This code:

name, age, country, career = ('Diana',32,'Canada','CompSci')
print(country)

does this:

name = 'Diana'
age = 32
country = 'Canada'
career = 'CompSci'

Tuples are not mutable, but you haven't made a tuple. To make a tuple, try this:

nameAge = ('Diana', 32)

now you change it:

>>> nameAge[1] = 33
Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    nameAge[1] = 'a'
TypeError: 'tuple' object does not support item assignment

As you can see, this tuple doesn't change.

Tags:

Python

Tuples