How To Assign Multiple Values In Python Variables?

Share Your Love

Many Values To Multiple Variables:

In python we can assign multiple values to multiple variables in a single line of code.

x, y, z = "Ram", "Shyam", "Gopal"

print(x)
print(y)
print(z)

The output of above code,

#Output
Ram
Shyam
Gopal

Here, a very important point you note down that the number of values is equal to the number of variables declare, otherwise it will generate an error.

One Value To Multiple Variables:

You can assign single value to multiple variables in single line of code.

x = y = z = "Rahul"

print(x)
print(y)
print(z)

The output of above code

Rahul
Rahul
Rahul

Unpacking A Collection:

If you have a collection of values in form of list or tuple(tuple and lists are python collection), then python extracts the values assigned to the variables. This is called unpacking.

fruits = ["Hello", "World", "Python"]
x, y, z = fruits

print(x)
print(y)
print(z)

Here the fruits object assign his values to multiple variables.

#Output
Hello
World
Python

Please write comments or WhatsApp if you find anything incorrect, or you want to share more information about the topic discussed above.

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 411

Newsletter Updates

Enter your email address below to subscribe to our newsletter