Python | Unpack the list of tuples

Python Methods and Functions

Let's discuss some methods to unpack a list of tuples.

Method # 1: Using a comprehension list

Using a list comprehension — the most naive approach to accomplish this unpacking task and is not usually used for this task, but a good method to start with.

Output:

 Original list is: [('Akshat', 1), (' Bro', 2), ('is', 3), (' Placed', 4)] Modified list is: [['Akshat',' Bro', 'is',' Placed'], [1, 2, 3, 4 ]] 

Method # 2: Using the zip () and * operators

Basically, the method is used to unpacking and most are Pythonic and recommended as well. This method is commonly used to accomplish this task by programmers throughout. * The operator unpacks tuples into independent lists.

# Python3 demo code
# Unpack the list of tuples
# use comprehension list

 
# initializing the list of tuples

test_list = [( 'Akshat' , 1 ), ( 'Bro' , 2 ), ( 'is' , 3 ), ( 'Placed' , 4 )]

 
# Print original list

print ( "Original list is:" + str (test_list))

 
# using a list comprehension for
# unpack

res = [[i for i, j in test_list],

[j for i, j in test_list]]

 
# Print modified list

print ( "Modified list is:" + str (res))

# Python3 demo code
# Unpack the list tuples
# using the zip () and * operator

 
# initializing the list of tuples

test_list = [( 'Akshat' , 1 ), ( ' Bro' , 2 ), ( 'is' , 3 ), ( 'Placed' , < / code> 4 )]

 
# Print original list

print ( "Original list is:" + str (test_list))

 
# using zip () and the * operator for
# unpack

res = list ( zip ( * test_list))

 
# Print modified list

print ( "Modified list is:" + str (res))

Output:

 Original list is: [('Akshat', 1), (' Bro', 2), ('is', 3) , ('Placed', 4)] Modified list is: [(' Akshat', 'Bro',' is', 'Placed'), (1, 2, 3, 4)] 

Method # 3: Using map ()
This is another method that can be used to accomplish this unzipping task, which is lesser known but is actually way to achieve this task. It also uses the * operator for basic list unpacking. This function is deprecated in Python & gt; = 3 versions.

# Python code for demonstration
# Unpack the tuple list
# using map ()

 
# initializing the list of tuples

test_list = [( ' Akshat' , 1 ), ( 'Bro' , 2 ), ( 'is' , 3 ), ( 'Placed' , 4 ) ]

 
# Print original list

print ( "Original list is:" + str (test_list))

  
# using map () for
# unpack

res = map ( None , * test_list)

 
# Print the modified list

print ( "Modified list is:" + str (res))

Output:

 Original list is: [( 'Akshat', 1), (' Bro', 2), ('is', 3), (' Placed', 4)] Modified list is: [('Akshat',' Bro', 'is',' Placed'), (1, 2, 3, 4)] 




Get Solution for free from DataCamp guru