DEV Community

bluepaperbirds
bluepaperbirds

Posted on

multiple assignment in Python

hey people what's going on? hope you're doing well.

i'm going to explain multiple assignment in python, so sit back relax and enjoy the article.

multiple assignment allows us to assign multiple variables at the same time using one line of code.

here's an example of us using standard assignment. let's say we have a variable name and i will set this to a value of my name.

name = "Tux"
print(name)
Enter fullscreen mode Exit fullscreen mode

let's say edge equals 21 and how about a variable called attractive?

name = "Tux"
edge = 21
attractive = True
Enter fullscreen mode Exit fullscreen mode

i think i'm gonna set this to true okay, so we have a bunch of variables and then we can print the value of these variables with some print statements.

print(name)
print(edge)
print(attractive)
Enter fullscreen mode Exit fullscreen mode

so let's print name age and attractive. so we have name age attractive and as you would expect this prints tux 21 and true.

now another way in which we could write the same code is to use multiple assignment and this allows usto assign multiple variables at the same time using one line of code.

surprised cat

so i'm going to turn all of these lines into comments and this time we will only use one line of code.

# name = "Tux"
# edge = 21
# attractive = True
Enter fullscreen mode Exit fullscreen mode

But to do this we're going to list all of our variables separated with a comma so that would be name comma edge comma attractive.

We will set them equal to those values but in the same order separated by commas so that would be tux comma 21 comma true and this would do the same thing, only using one line of code.

name, edge, attractive = "Tux", 21, True
Enter fullscreen mode Exit fullscreen mode

You can print the variables on one line too

>>> name,edge,at = "Tux",21,True
>>> print(name, edge, at)
Tux 21 True
>>> 
Enter fullscreen mode Exit fullscreen mode

If you have a large program or use loops/if statements keep in mind the variable scope

Top comments (0)