Python Multiple Assignment 🎯

beginner
25 min

Python Multiple Assignment 🎯

Welcome to our comprehensive guide on Python Multiple Assignment! In this lesson, we'll explore how to assign multiple values to variables at once in Python. This is a fundamental concept that will make your code more efficient and easier to understand.

What is Multiple Assignment? 📝

Multiple assignment is a way to assign multiple values to variables simultaneously in Python. It's a shorthand that helps you save time and make your code more readable.

Why Multiple Assignment? 💡

Multiple assignment can be especially useful when you have related variables that are derived from the same operation or when you're dealing with tuples or lists. It simplifies your code and makes it more concise.

How to Perform Multiple Assignment? 🎯

Let's dive into an example:

python
# Assigning values to variables a, b, and c a, b, c = 1, 2, 3 # Verifying the assigned values print("a =", a) # Output: a = 1 print("b =", b) # Output: b = 2 print("c =", c) # Output: c = 3

In the example above, we assigned the values 1, 2, and 3 to variables a, b, and c respectively. Notice how Python automatically assigns the values in the order they are given.

Multiple Assignment with Lists and Tuples 💡

You can also perform multiple assignment with lists and tuples:

python
# Assigning values from a list to variables a, b, and c my_list = [1, 2, 3, 4, 5] a, b, c, d, e = my_list # Verifying the assigned values print("a =", a) # Output: a = 1 print("b =", b) # Output: b = 2 print("c =", c) # Output: c = 3 print("d =", d) # Output: d = 4 print("e =", e) # Output: e = 5

In this example, we assigned the values from the list my_list to variables a, b, c, d, and e respectively.

Multiple Assignment with Functions 💡

You can also use multiple assignment with function returns:

python
def my_function(): return 1, 2, 3 # Assigning values from the function to variables a, b, and c a, b, c = my_function() # Verifying the assigned values print("a =", a) # Output: a = 1 print("b =", b) # Output: b = 2 print("c =", c) # Output: c = 3

In this example, we defined a function my_function() that returns a tuple with three elements. We then used multiple assignment to assign these elements to variables a, b, and c.

Quiz 🎯

Quick Quiz
Question 1 of 1

What does Python call multiple assignment?


By understanding and applying multiple assignment in your Python code, you'll write cleaner, more efficient code that is easier to read and understand. Happy coding! 💪