Multiple Assignments


Multiple Assignments

We can assign one value to multiple variables on a single statement in the Python programming language. This is known as multiple assignments. 
Multiple assignments are also called tuple unpacking or iterable unpacking. In a single line of code, you can assign a value to multiple variables simultaneously. The use of parentheses is optional in multiple assignments.
Multiple assignments are called "tuple-unpacking" because it is usually practiced with tuples. However, we can also use multiple assignments with some other iterable, not only tuples. 

Unwrapping in a for loop:

Multiple assignments are most ordinarily used in for loops.

Multiple assignments are an alternative to difficult-coded indexes:

If you notice Python code that practices complex coded indexes, they usually practice multiple assignments to simplify the code and make it readable and understandable.

Strictness in Multiple assignments:

The Multiple assignments are somewhat strict if it lands in unpacking the iterable we give to it

  • When we try to unpack a bigger iterable into a shorter amount of variables, we will receive an error fairly.
  • When we try to unpack a smaller iterable into a larger amount of variables, we will probably receive an error.

The strictness in multiple assignments is pretty excellent. When we are operating with an item with a distinctive size than we supposed, the multiple assignments will crash aloud. And we get to know about a bug in the program positively that we won't be yet aware of.

Example No.1:

a, b = 100, 200 print(a) print(b)

OUTPUT:

100
200

Example No.2:

a, b = 'knowledge2life', 'website' print(a) print(b)

OUTPUT:

knowledge2life
website