Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: multiple variables using tuple

Tags:

python

tuples

I was reading about tuple:

Once created, the values of a tuple cannot change.

If you want to assign multiple variables at once, you can use tuples:

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

I did this..

country = 'India'
print(country)

and it's modified. How come?

like image 711
Shri Avatar asked May 13 '16 13:05

Shri


1 Answers

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.

like image 50
Philip Feldmann Avatar answered Sep 29 '22 23:09

Philip Feldmann