Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Assign multiple variables with a Python list values
Python allows you to assign multiple variables from a list in several ways. This is useful when you need to extract specific values from a list and use them as separate variables in your program.
Using List Comprehension with Indexing
You can use list comprehension to select specific elements by their index positions and assign them to variables ?
schedule = ['Mon', ' 2pm', 1.5, '11 miles']
# Given list
print("Given list:", schedule)
# Using list comprehension with specific indices
day, hours, distance = [schedule[i] for i in (0, 2, 3)]
# Result
print("The variables:", day + ", " + str(hours) + ", " + distance)
Given list: ['Mon', ' 2pm', 1.5, '11 miles'] The variables: Mon, 1.5, 11 miles
Using itemgetter from operator Module
The itemgetter function extracts items at specified indices and returns them as a tuple, which can be unpacked into variables ?
from operator import itemgetter
schedule = ['Mon', ' 2pm', 1.5, '11 miles']
# Given list
print("Given list:", schedule)
# Using itemgetter
day, hours, distance = itemgetter(0, 2, 3)(schedule)
# Result
print("The variables:", day + ", " + str(hours) + ", " + distance)
Given list: ['Mon', ' 2pm', 1.5, '11 miles'] The variables: Mon, 1.5, 11 miles
Using itertools.compress
The compress function filters elements using boolean values. Use 1 (True) for positions you want and 0 (False) for positions to skip ?
from itertools import compress
schedule = ['Mon', ' 2pm', 1.5, '11 miles']
# Given list
print("Given list:", schedule)
# Using compress with boolean selector
day, hours, distance = compress(schedule, (1, 0, 1, 1))
# Result
print("The variables:", day + ", " + str(hours) + ", " + distance)
Given list: ['Mon', ' 2pm', 1.5, '11 miles'] The variables: Mon, 1.5, 11 miles
Simple Unpacking (Bonus Method)
For consecutive elements, you can use simple unpacking with slicing ?
data = ['apple', 'banana', 'cherry']
# Simple unpacking
fruit1, fruit2, fruit3 = data
print("Fruits:", fruit1, fruit2, fruit3)
# Partial unpacking with underscore for unwanted values
first, _, third = data
print("Selected fruits:", first, third)
Fruits: apple banana cherry Selected fruits: apple cherry
Comparison
| Method | Best For | Readability |
|---|---|---|
| List comprehension | Non-consecutive indices | Good |
| itemgetter | Multiple extractions | Excellent |
| compress | Boolean-based selection | Moderate |
| Simple unpacking | All or consecutive elements | Excellent |
Conclusion
Use itemgetter for clean, readable code when extracting specific indices. Use simple unpacking for consecutive elements, and list comprehension for more complex index patterns.
