Multi-Assignment in Python
Hello guyz welcome back to thecodingproject after a loong loong time 😌. This past couple of days I was very busy in my other projects and some personal stuff so could not get much time to post anything here but now I am back and I have another topic in #python to deal with.
Today we are going to explore what is “Multi-Assignment”. It’s better to get straight into an example. Let’s consider three variables k.l & m and a list [1,2,3]. Now when you do the following in the python prompt -
k,l,m = [1,2,3]
Print(k)
print(l)
print(m)
Output is :
1
2
3
|
Here each variable (k,l,m) are assigned to each element in the list in that order. That’s why when you type in k you get 1, l gets you 2 and m gets you 3. Instead when you do the following -
k,l,m = 1
You will get the following error-
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'int' object is not iterable
The above error occurs because you now have three variable objects k,l & m but you want to assign only a single integer object 1 to all the three variables. So, python can’t iterate through a single object for all the three variables.
But when you do this instead-
k,l,m= 2,3,4
And then you type the following -
>>> k
2
>>> l
3
>>> m
4
The concept here is simple. In you example when you assign k,l & m to the list [1,2,3] then python iterates through the list and assigns the list elements to the variables in that order. In the last example when you assign k,l & m to the objects 2,3 & 4, python again iterates through the sequence of integer objects and assigns them to the variables. So, whenever you do such assignments python iterates through the sequence of objects and assigns the reference of the address of these objects to the variables one by one.
k,l,m = 1
You will get the following error-
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'int' object is not iterable
The above error occurs because you now have three variable objects k,l & m but you want to assign only a single integer object 1 to all the three variables. So, python can’t iterate through a single object for all the three variables.
But when you do this instead-
k,l,m= 2,3,4
And then you type the following -
>>> k
2
>>> l
3
>>> m
4
The concept here is simple. In you example when you assign k,l & m to the list [1,2,3] then python iterates through the list and assigns the list elements to the variables in that order. In the last example when you assign k,l & m to the objects 2,3 & 4, python again iterates through the sequence of integer objects and assigns them to the variables. So, whenever you do such assignments python iterates through the sequence of objects and assigns the reference of the address of these objects to the variables one by one.
So, folks this was all for this week but more stuffs are coming your way next week, til then happy coding.
Comments
Post a Comment