In this article, you’ll learn about two variants of this problem.
- Assign multiple values to multiple variables
- Assign the same value to multiple variables
Let’s have a quick overview of both in our interactive code shell:
Exercise: Increase the number of variables to 3 and create a new one-liner!
Let’s dive into the two subtopics in more detail!
Assign Multiple Values to Multiple Variables [One-Liner]
You can use Python’s feature of multiple assignments to assign multiple values to multiple variables. Here is the minimal example:
a, b = 1, 2 print(a) # 1 print(b) # 2 You can use the same syntax to assign three or more values to three or more variables in a single line of code:
a, b, c, d = 1, 2, 3, 4 print(a, b, c, d) # 1 2 3 4
Most coders would consider this more readable and concise than the multi-liner:
a = 1 b = 2 c = 3 d = 4 print(a, b, c, d) # 1 2 3 4
Explanation Multiple Assignment
The syntax of multiple assignments works as follows.
- By using a comma-separated sequence of values on the right side of the equation, you create a tuple on the right side.
- Now, you unpack the tuple into the variables declared on the left side of the equation.
Here’s a minimal code example that shows that you can create a tuple without the usual parentheses syntax:
>>> a = 1, 2 >>> print(a) (1, 2) >>> print(type(a)) <class 'tuple'>
This explains why the multiple assignment operator is not something you need to remember—if you have understood its underlying concept.
The unpacking syntax in Python is important for many other Python features. It works as follows: you extract an iterable of multiple values into an outer structure of multiple variables.
You can also combine it by unpacking, say, three values into two variables:
*a, b = 1, 2, 3 print(a) # [1, 2] print(b) # 3
The asterisk operator placed in front of a variable tells Python to unpack as many values into this variable as possible. Remember, there’s a tuple on the right side of the equation with three values. Python recognizes that the third value will be placed into variable
b. The other two values must be placed into variable
a to produce a valid assignment.
Note that it’s not required that all the values in your multiple assignment one-liner have the same type:
a, b, c = 'hello', 42, 3.14 print(a, b, c) # hello 42 3.14
The first value has type string, the second value has type integer, and the third value has type float.
But be careful, if the number of variables on the left do not match the number of values in the iterable on the right, Python throws a
Here’s an example:
a, b, c = 1, 2 ''' Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 1, in <module> a, b, c = 1, 2 ValueError: not enough values to unpack (expected 3, got 2) '''
Assign the Same Value to Multiple Variables [One-Liner]
You can use multiple
= symbols to assign multiple values to multiple variables. Just create a chain of assignments like this:
a = b = 1 print(a) # 1 print(b) # 1
This also works for more than two variables:
a = b = c = [1, 2, 3] print(a) # [1, 2, 3] print(b) # [1, 2, 3] print(c) # [1, 2, 3]
In this example, you assign the same object (a Python list) to all three variables.
Python One-Liners Book: Master the Single Line First!
Python programmers will improve their computer science skills with these useful one-liners.
Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.
Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.
You’ll also learn how to:
- Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
- Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
- Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
- Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
- Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.