How do we assign a value to several variables simultaneously in Python?

PythonServer Side ProgrammingProgramming

In Python, variable is really a label or identifier given to object stored in memory. Hence, same object can be identified by more than one variables.

>>> a=b=c=5
>>> a
5
>>> b
5
>>> c
5

a, b and c are three variables all referring to same object. This can be verified by id() function.

>>> id(a), id(b), id(c)
(1902228672, 1902228672, 1902228672)

Python also allows different values to be assigned to different variables in one statement. Values from a tuple object are unpacked to be assigned to multiple variables.

>>> a,b,c=(1,2,3)
>>> a
1
>>> b
2
>>> c
3
raja
Published on 02-Jan-2018 18:59:49
Advertisements