Python Tutorial > Python Basics > Python Variables (Part 2): Assign Multiple Values to a Variable
Posted in

Python Variables (Part 2): Assign Multiple Values to a Variable

Python Variables (Part 2)
Assign Multiple Values to a Variable

Previous Tutorial: Python Variables (Part 1)

Python Variables

Variable Names are Case-Sensitive

CODE:
firstname = 'Python'
print(Firstname)
OUTPUT:
NameError: name 'Firstname' is not defined.
CODE:
firstname = 'Python'
Firstname = 'Java'
CODE:
text1 = 'Python'
texT1 = 'Java'
print(text1)
print(texT1)
OUTPUT:
Python
Java

Variables are Dynamically Typed

CODE:
num = 1000
CODE:
num = 1000
num = 'Python'
CODE:
num = 1000
print(num)
num = "Python"
print(num)
OUTPUT:
1000
Python

Assign Multiple Values to a Variable

Assign Multiple Values to Multiple Variables

CODE:
text1, text2, text3 = 'Python', 'Java', 'PHP'
print(text1, text2, text3)
OUTPUT:
Python Java PHP
CODE:
text1, text2, text3 = 'Python', 'Java'
print(text1, text2, text3)
OUTPUT:
ValueError: not enough values to unpack (expected 3, got 2)

Assign One Value to Multiple Variables

CODE:
text1 = text2 = text3 = 'Python'
print(text1)
print(text2)
print(text3)
OUTPUT:
Python
Python
Python
CODE:
text1 = text2 = text3 = 'Python', 'Java'
print(text1)
print(text2)
print(text3)
OUTPUT:
('Python', 'Java')
('Python', 'Java')
('Python', 'Java')

Assign Multiple Values to One Variable

CODE:
text1 = 'Python', 'Java', 'PHP'
print(text1)
OUTPUT:
('Python', 'Java', 'PHP')
CODE:
text1 = 'Python', 'Java', 'PHP'
print(text1)
print(type(text1))
OUTPUT:
('Python', 'Java', 'PHP')
<class 'tuple'>

How to Unpack a List Collection into Variables

CODE:
animals = ['Cow', 'Dog', 'Cat']
a, b, c = animals
print(a)
print(b)
print(c)
OUTPUT:
Cow
Dog
Cat
CODE:
animals = ['Cow', 'Dog', 'Cat']
a, b = animals
print(a)
print(b)
print(c)
OUTPUT:
ValueError: too many values to unpack (expected 2)
CODE:
animals = ['Cow', 'Dog', 'Cat', 'Rat']
a, *b = animals
print(a)
print(b)
OUTPUT:
Cow
['Dog', 'Cat', 'Rat']
CODE:
animals = ['Cow', 'Dog', 'Cat', 'Rat']
*a, b = animals
print(a)
print(b)
OUTPUT:
['Cow', 'Dog', 'Cat']
Rat
CODE:
animals = ['Cow', 'Dog', 'Cat', 'Rat']
a, *b, c = animals
print(a)
print(b)
print(c)
OUTPUT:
Cow
['Dog', 'Cat']
Rat
CODE:
animals = ['Cow', 'Dog', 'Cat', 'Rat']
a, *b, *c = animals
print(a)
print(b)
print(c)
OUTPUT:
SyntaxError: multiple starred expressions in assignment

Conclusion

Next Tutorial: Python Variable (Part3)

Summary
Python Variables (Part 2): Assign Multiple Values to a Variable
Article Name
Python Variables (Part 2): Assign Multiple Values to a Variable
Description
In this tutorial, we are going to learn about how to assign multiple values to multiple variables in Python. Also learned how to unpack a collection in Python.
Author
Publisher Name
anotherdaywithpython.in
Publisher Logo

Leave a Reply

Your email address will not be published. Required fields are marked *