How to unpack List in Python? [3 Methods with Examples]
Table of Contents
Introduction to Unpacking in python
Unpacking is the process of assigning values from an iterable (such as a list or tuple) to a set of variables. When we unpack a list, we assign the individual element in the list to a separate variable.
Unpacking list can be useful in many cases such as –
- Assigning multiple variables at once
- Swapping variable values
- Looping over a list
Table of Contents
Different Types of Unpacking in Python:
Unpacking list using 2 variables
Assigning the elements of a list to two separate variables is known as unpacking a list using two variables. This is also known as tuple unpacking, because the elements of the list are unpacked into a tuple.
For Example:
Colors = ["Red" , "Yellow"]
color1 , color2 = Colors
print(color1)
print(color2)
Output:
Red
Yellow
Unpacking a Nested List
colors = [["MG" , "Yellow"] , ["BMW" , "Red"] , ["Suzuki" , "Black"]]
for car , col in colors :
print( car , "is in" , col ,"color")
Output:
MG is in Yellow color
BMW is in Red color
Suzuki is in Black color
Unpacking list using 3 variables
Assigning the elements of a list to three separate variables is known as unpacking a list using three variables.This can be useful in many scenarios where the elements of list are fixed and dimensions are constant.
For Example –
Imagine you have a Csv file with the following information and using the list unpacking we can convert the elements of the list into 3 separate variables.
users.csv
Name | Age | |
John | [email protected] | 23 |
Mark | [email protected] | 25 |
Stacy | [email protected] | 21 |
Capi | [email protected] | 27 |
Code:
import csv
with open('users.csv') as f:
file_row = csv.reader(f)
for name, email , age in file_row:
print(name,email, age)
Output:
Name Email Age
John [email protected] 23
Mark [email protected] 25
Stacy [email protected] 21
Capi [email protected] 27
Unpacking list using * (Asterisk)
* (asterisk) is used to unpack the multiple elements of a list or tuple into a single variable. This feature is called “extended iterable unpacking,” and it allows you to assign some or all of the elements of a list to separate variables.
For Example:
words = ["Hello" , "Goom" , "Python" , "Learn" ,"Create"]
greet , *goom = wordsprint(greet)
print(goom)
Output:
Hello['Goom', 'Python', 'Learn', 'Create']
Example 2:
shapes = ["square" , "circle" , "rectangle" , "trapezium" , "cuboid"]
first , second , *rest = shapesprint(first)
print(second)
print(rest)
Output –
square
circle
['rectangle', 'trapezium', 'cuboid']
Unpacking list using Named tuple
Named tuples are a special kind of tuple provided by the collections module in Python. They are similar to python default tuples but the elements inside the tuples are accessible using index as well as their name.
For Example –
from collections
import namedtuple
Book = namedtuple('Book', ['name', 'genre', 'pages'])
B = Book('Harry Potter', 'Fiction', '254')
print("Using index - ")
print(B[0])
print(B[1])
print(B[2])
print("Using Name -")
print(B.name)
print(B.genre)
print(B.pages)
Output –
Using index -
Harry Potter
Fiction
254
Using Name -
Harry Potter
Fiction
254
Errors While working with list unpacking
ValueError:
not enough values to unpack (expected n, got m) –
This error occurs when you try to unpack a string into too few variables.
For example:
Colours = ["Red" , "Blue" , "Green"]
r , b = Colours
print(r)
print(b)
Output:
File "/home/main.py", line 2, in <module>
ValueError: too many values to unpack (expected 2)
This error can be avoided either using the correct number of variables or using the reference variable at the end to handle all the extra elements in the list.