Given a list of tuples, write a Python program to convert it into list.
Examples:
Input: [(11, 20), (13, 40), (55, 16)] Output:[11, 20, 13, 40, 55, 16] Input: [('Geeks', 2), ('For', 4), ('geek', '6')] Output: ['Geeks', 2, 'For', 4, 'geek', '6']
Below are methods to convert list of tuples into list.
Method #1 : Using list comprehension
# Python code to convert list of tuples into list # List of tuple initialization lt = [( 'Geeks' , 2 ), ( 'For' , 4 ), ( 'geek' , '6' )] # using list comprehension out = [item for t in lt for item in t] # printing output print (out) |
['Geeks', 2, 'For', 4, 'geek', '6']
Method #2 : Using itertools
# Python code to convert list of tuple into list # Importing import itertools # List of tuple initialization tuple = [( 1 , 2 ), ( 3 , 4 ), ( 5 , 6 )] # Using itertools out = list (itertools.chain( * tuple )) # printing output print (out) |
[1, 2, 3, 4, 5, 6]
Method #3 : Using iteration
# Python code to convert list of tuple into list # List of tuple initialization tup = [( 1 , 2 ), ( 3 , 4 ), ( 5 , 6 )] # result list initialization result = [] for t in tup: for x in t: result.append(x) # printing output print (result) |
[1, 2, 3, 4, 5, 6]
Method #4 : Using sum
# Python code to convert list of tuple into list # List of tuple initialization tup = [( 1 , 2 ), ( 3 , 4 ), ( 5 , 6 )] # using sum function() out = list ( sum (tup, ())) # printing output print (out) |
[1, 2, 3, 4, 5, 6]
Method #5 : Using operator and reduce
# Python code to convert list of tuple into list import operator from functools import reduce # List of tuple initialization tup = [( 1 , 2 ), ( 3 , 4 ), ( 5 , 6 )] # printing output print ( list ( reduce (operator.concat, tup))) |
[1, 2, 3, 4, 5, 6]
Method #6 : Using lambda
# Python code to convert list of tuple into list # List of tuple initialization tup = [( 1 , 2 ), ( 3 , 4 ), ( 5 , 6 )] # Using map for 0 index b = map ( lambda x: x[ 0 ], tup) # Using map for 1 index c = map ( lambda x: x[ 1 ], tup) # converting to list b = list (b) c = list (c) # Combining output out = b + c # printing output print (out) |
[1, 3, 5, 2, 4, 6]
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.