Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python – Add Custom Column to Tuple list

  • Last Updated : 10 Jun, 2020

Sometimes, while working with Python records, we can have a problem in which we need to add custom column to tuples list. This kind of problem can have application in data domains such as web development. Lets discuss certain ways in which this task can be performed.

Input :
test_list = [(3, ), (7, ), (2, )]
cus_eles = [7, 8, 2]
Output : [(3, 7), (7, 8), (2, 2)]

 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. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Input :
test_list = [(3, 9, 6, 10)]
cus_eles = [7]
Output : [(3, 9, 6, 10, 7)]



Method #1 : Using list comprehension + zip()
The combination of above functionalities can be used to solve this problem. In this, we perform the pairing of custom elements and tuples with the help of zip().




# Python3 code to demonstrate working of 
# Add Custom Column to Tuple list
# Using list comprehension + zip()
  
# initializing list
test_list = [(3, 4), (78, 76), (2, 3)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing add list
cus_eles = [17, 23, 12]
  
# Add Custom Column to Tuple list
# Using list comprehension + zip()
res = [sub + (val, ) for sub, val in zip(test_list, cus_eles)]
  
# printing result 
print("The tuples after adding elements : " + str(res)) 
Output :
The original list is : [(3, 4), (78, 76), (2, 3)]
The tuples after adding elements : [(3, 4, 17), (78, 76, 23), (2, 3, 12)]

 

Method #2 : Using map() + lambda
The combination of above functions can also be used to solve this problem. In this, we perform the task of extending logic to each tuple using map() and lambda is used to perform task of addition.




# Python3 code to demonstrate working of 
# Add Custom Column to Tuple list
# Using map() + lambda
  
# initializing list
test_list = [(3, 4), (78, 76), (2, 3)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing add list
cus_eles = [17, 23, 12]
  
# Add Custom Column to Tuple list
# Using map() + lambda
res = list(map(lambda a, b: a +(b, ), test_list, cur_eles))
  
# printing result 
print("The tuples after adding elements : " + str(res)) 
Output :
The original list is : [(3, 4), (78, 76), (2, 3)]
The tuples after adding elements : [(3, 4, 17), (78, 76, 23), (2, 3, 12)]



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!