Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Convert String to tuple list
Next article icon

Python | Convert Lists to column tuples

Last Updated : 30 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, while working with data, we can have a problem in which we need to get alike index elements in a single container. This means the columns of Matrix/Multiple lists need to be converted to list of tuples, each comprising of like index elements. Let's discuss certain ways in which this task can be done. 

Method #1 : Using zip() + list comprehension The combination of above functions can work together to achieve this particular task. In this, we combine the like index elements into column using zip(), and binding all tuples into a list and iteration of dictionary lists is performed by list comprehension. 

Python3
# Python3 code to demonstrate working of  # Convert Lists to column tuples  # using zip() + list comprehension   # initialize dictionary  test_dict = {'list1' : [1, 4, 5],              'list2' : [6, 7, 4],              'list3' : [9, 1, 11]}   # printing original dictionary  print("The original dictionary is : " + str(test_dict))   # Convert Lists to column tuples  # using zip() + list comprehension  res = list(zip(*(test_dict[key] for key in test_dict.keys())))   # printing result  print("Like index column tuples are : " + str(res))  

Output
The original dictionary is : {'list1': [1, 4, 5], 'list2': [6, 7, 4], 'list3': [9, 1, 11]} Like index column tuples are : [(1, 6, 9), (4, 7, 1), (5, 4, 11)]

Time Complexity: O(n*n) where n is the number of elements in the list “test_list”. AND operation - Using zip() + list comprehension performs n*n number of operations.
Auxiliary Space: O(n), extra space is required where n is the number of elements in the list

Method #2 : Using zip() + values() The combination of above functions can be used to perform this task. In this, we access the values of dictionary values using the values() and aggregating columns can be done using zip(). 

Python3
# Python3 code to demonstrate working of  # Convert Lists to column tuples  # using zip() + values()   # initialize dictionary  test_dict = {'list1' : [1, 4, 5],              'list2' : [6, 7, 4],              'list3' : [9, 1, 11]}   # printing original dictionary  print("The original dictionary is : " + str(test_dict))   # Convert Lists to column tuples  # using zip() + values()  res = list(zip(*test_dict.values()))   # printing result  print("Like index column tuples are : " + str(res))  

Output
The original dictionary is : {'list1': [1, 4, 5], 'list2': [6, 7, 4], 'list3': [9, 1, 11]} Like index column tuples are : [(1, 6, 9), (4, 7, 1), (5, 4, 11)]

Method #3: Using numpy.column_stack()

Note: Install numpy module using command "pip install numpy"

Using numpy.column_stack() converts lists to column tuples by using the numpy.column_stack() function. The method first imports the numpy library, then initializes a dictionary "test_dict" containing three lists. Then it prints the original dictionary. The numpy.column_stack() function is then used to stack the lists in the dictionary side by side. It takes a list of lists and forms a 2D array by stacking the input lists as columns.

Python3
# Method #4: Using numpy.column_stack()  import numpy as np  # initialize dictionary test_dict = {'list1': [1, 4, 5],              'list2': [6, 7, 4],              'list3': [9, 1, 11]}  # printing original dictionary print("The original dictionary is : " + str(test_dict))  # Convert Lists to column tuples # using numpy.column_stack() res = np.column_stack([test_dict[key] for key in test_dict.keys()][::-1])  # printing result print("Like index column tuples are : " + str(res))   #This code is contributed by Edula Vinay Kumar Reddy 

Output:

The original dictionary is : {'list1': [1, 4, 5], 'list2': [6, 7, 4], 'list3': [9, 1, 11]} Like index column tuples are : [[ 9  6  1] [ 1  7  4] [11  4  5]]

Time complexity: O(n) where n is the number of elements in the lists as numpy.column_stack() is a constant time operation, regardless of the number of input lists. 
Auxiliary space: O(n) as it creates a new 2D array of tuples.

Method #4: Using pandas.DataFrame

Pandas is a popular library for data manipulation and analysis in Python. We can use the DataFrame function of pandas to create a table from the dictionary and then select the columns to create tuples. 

Here is the step-by-step approach:

  • Import the pandas library.
  • Create a pandas DataFrame from the dictionary using the from_dict() method.
  • Select the columns using the loc[] accessor.
  • Convert the DataFrame to a list of tuples using the to_records() method.
Python3
# Python3 code to demonstrate working of  # Convert Lists to column tuples  # using pandas.DataFrame  # import pandas library import pandas as pd  # initialize dictionary test_dict = {'list1' : [1, 4, 5],              'list2' : [6, 7, 4],              'list3' : [9, 1, 11]}  # printing original dictionary print("The original dictionary is : " + str(test_dict))  # create pandas DataFrame from dictionary df = pd.DataFrame.from_dict(test_dict)  # select columns and convert to list of tuples res = list(df.loc[:, ['list1', 'list2', 'list3']].to_records(index=False))  # printing result print("Like index column tuples are : " + str(res)) 

Output:

The original dictionary is : {'list1': [1, 4, 5], 'list2': [6, 7, 4], 'list3': [9, 1, 11]} Like index column tuples are : [(1, 6, 9), (4, 7, 1), (5, 4, 11)]

Time complexity: O(n), where n is the number of key-value pairs in the dictionary. 
Auxiliary space: O(n), where n is the number of key-value pairs in the dictionary. 

Method #5 : Using nested for loop + values() method

Step-by-step approach:

  • Extract values of dictionary using values() method
  • Use nested for loops to convert values list to like index column tuples
  • Display column tuples
Python3
# Python3 code to demonstrate working of # Convert Lists to column tuples  # initialize dictionary test_dict = {'list1' : [1, 4, 5],             'list2' : [6, 7, 4],             'list3' : [9, 1, 11]}  # printing original dictionary print("The original dictionary is : " + str(test_dict))  # Convert Lists to column tuples x=list(test_dict.values()) res=[] for i in range(0,len(x)):     v=[]     for j in range(0,len(x[i])):         v.append(x[j][i])     res.append(tuple(v))          # printing result print("Like index column tuples are : " + str(res)) 

Output
The original dictionary is : {'list1': [1, 4, 5], 'list2': [6, 7, 4], 'list3': [9, 1, 11]} Like index column tuples are : [(1, 6, 9), (4, 7, 1), (5, 4, 11)]

Time Complexity: O(M*N) M - length of values list N - length of each list in value list
Auxiliary Space: O(M*N) M - length of values list N - length of each list in value list

Method #6 : Using heapq :

 Algorithm :

  1. Initialize the dictionary test_dict with three keys list1, list2, and list3, each having a list of integers as its value.
  2. Print the original dictionary test_dict.
  3. Create an empty list res to store the tuples of columns.
  4. Iterate over each index i of the lists in test_dict using a for loop, where i goes from 0 to the length of any list in test_dict.
  5. Inside the loop, use a list comprehension to extract the values at index i from each list in test_dict.
  6. Pass the resulting list of extracted values to the heapq.nsmallest() function to get the n smallest elements, where n is the length of test_dict.
  7. Store the resulting list of smallest elements in the temp variable.
  8. Convert temp to a tuple and append it to the res list.
  9. Repeat steps 5-8 for all indices i.
  10. Print the resulting list res, which contains tuples with elements corresponding to the original lists in test_dict at the same index.
Python3
import heapq  # initialize dictionary test_dict = {'list1': [1, 4, 5], 'list2': [6, 7, 4], 'list3': [9, 1, 11]}  # printing original dictionary print("The original dictionary is : " + str(test_dict))  # Convert Lists to column tuples using heapq method res = [] for i in range(len(test_dict)):     temp = heapq.nsmallest(len(test_dict), [test_dict[key][i] for key in test_dict])     res.append(tuple(temp))  # printing result print("Like index column tuples are : " + str(res)) #This code is contributed by Jyothi pinjala. 

Output
The original dictionary is : {'list1': [1, 4, 5], 'list2': [6, 7, 4], 'list3': [9, 1, 11]} Like index column tuples are : [(1, 6, 9), (1, 4, 7), (4, 5, 11)]

Time complexity:

The for loop iterates over len(test_dict) elements, which is the length of any list in test_dict.
The list comprehension extracts the values at the current index from each list in test_dict, taking O(len(test_dict)) time.
The heapq.nsmallest() function takes O(len(test_dict) log len(test_dict)) time to return the smallest n elements.
Therefore, the overall time complexity of the algorithm is O(len(test_dict)^2 log len(test_dict)).
Space complexity:

The space required to store the res list is O(len(test_dict)^2).
The space required to store the temp list is O(len(test_dict)).
Therefore, the overall space complexity of the algorithm is O(len(test_dict)^2).

Method #7: Using itertools:

Algorithm :

  1. Initialize a dictionary named test_dict containing three keys, each mapped to a list of integers.
  2. Print the original dictionary.
  3. Use itertools.zip_longest() method to combine the values of each key into tuples, filling missing values with -inf.
  4. Use map() and tuple() functions to convert the tuples of values into tuples of columns.
  5. Store the resulting tuples of columns in a list named res.
  6. Print the resulting list of tuples.
Python3
import itertools  # initialize dictionary test_dict = {'list1': [1, 4, 5], 'list2': [6, 7, 4], 'list3': [9, 1, 11]}  # printing original dictionary print("The original dictionary is : " + str(test_dict))  # Convert Lists to column tuples using itertools method res = list(map(tuple, itertools.zip_longest(*test_dict.values(), fillvalue=float('-inf'))))  # printing result print("Like index column tuples are : " + str(res)) #this code is contributed by Rayudu. 

Output
The original dictionary is : {'list1': [1, 4, 5], 'list2': [6, 7, 4], 'list3': [9, 1, 11]} Like index column tuples are : [(1, 6, 9), (4, 7, 1), (5, 4, 11)]

The time complexity : O(n*m) where n is the number of keys in test_dict and m is the length of the longest list among the values. This is because the zip_longest() method and map() function both iterate through each element of the lists, and the tuple() function has a constant time complexity.

The space complexity : O(m) because we are creating a new tuple for each column of values, and the size of each tuple is proportional to the length of the longest list among the values. Additionally, we are creating a new list to store the resulting tuples of columns.

Method #8: Using  reduce():

Algorithm:

  1. Initialize a dictionary test_dict with three keys and corresponding list values.
  2. Print the original dictionary.
  3. Use the zip_longest function from the itertools module to combine the lists in test_dict into tuples. The fillvalue parameter is set to -inf to ensure that all tuples have the same length, even if some lists are shorter than others.
  4. Use the reduce function from the functools module to convert the tuples into column tuples. The reduce function takes a lambda function as the first argument, which combines the current accumulator value (an empty list at the start) with the current value from the zip_longest iterator. The lambda function creates a new tuple with the three values in the current value and appends it to the accumulator.
  5. Print the resulting list of column tuples.
Python3
import itertools from functools import reduce  # initialize dictionary test_dict = {'list1': [1, 4, 5], 'list2': [6, 7, 4], 'list3': [9, 1, 11]}  # printing original dictionary print("The original dictionary is : " + str(test_dict))  # Convert Lists to column tuples using reduce method res = reduce(lambda x, y: x + [(y[0], y[1], y[2])], itertools.zip_longest(*test_dict.values(), fillvalue=float('-inf')), [])  # printing result print("Like index column tuples are : " + str(res)) #This code is contributed by vinay pinjala. 

Output
The original dictionary is : {'list1': [1, 4, 5], 'list2': [6, 7, 4], 'list3': [9, 1, 11]} Like index column tuples are : [(1, 6, 9), (4, 7, 1), (5, 4, 11)] 

Time complexity:

The zip_longest function iterates over the values in test_dict and creates tuples with fillvalue when necessary. The time complexity of zip_longest is O(n*m), where n is the number of keys in test_dict and m is the length of the longest list.
The reduce function iterates over the tuples created by zip_longest and applies the lambda function to them. The time complexity of reduce is O(n), where n is the number of tuples.
Therefore, the overall time complexity of the code is O(n*m).

Space complexity:

The zip_longest function creates tuples with fillvalue when necessary. The number of tuples created is the length of the longest list in test_dict. Therefore, the space complexity of zip_longest is O(m).
The reduce function creates a new list with the column tuples. The length of this list is equal to the number of tuples created by zip_longest. Therefore, the space complexity of reduce is also O(m).
Therefore, the overall space complexity of the code is O(m).


Next Article
Python | Convert String to tuple list
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Convert List to Tuple in Python
    The task of converting a list to a tuple in Python involves transforming a mutable data structure list into an immutable one tuple. Using tuple()The most straightforward and efficient method to convert a list into a tuple is by using the built-in tuple(). This method directly takes any iterable like
    2 min read
  • Python - Add Custom Column to Tuple list
    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,
    5 min read
  • Python | Convert String to tuple list
    Sometimes, while working with Python strings, we can have a problem in which we receive a tuple, list in the comma-separated string format, and have to convert to the tuple list. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop + split() + replace() This is a br
    5 min read
  • Python - Column Mapped Tuples to dictionary items
    Given Tuple Matrix of length 2, map each column's element value with next column and construct dictionary keys. Input : test_list = [[(1, 4), (6, 3), (4, 7)], [(7, 3), (10, 14), (11, 22)]] Output : {1: 7, 4: 3, 6: 10, 3: 14, 4: 11, 7: 22} Explanation : 1 -> 7, 4 -> 3.., as in same column and i
    4 min read
  • Python | Convert String to list of tuples
    Sometimes, while working with data, we can have a problem in which we have a string list of data and we need to convert the same to list of records. This kind of problem can come when we deal with a lot of string data. Let's discuss certain ways in which this task can be performed. Method #1: Using
    8 min read
  • Python | Convert Tuple to integer
    Sometimes, while working with records, we can have a problem in which we need to convert the data records to integer by joining them. Let's discuss certain ways in which this task can be performed. Method #1 : Using reduce() + lambda The combination of above functions can be used to perform this tas
    5 min read
  • Convert Dictionary to List of Tuples - Python
    Converting a dictionary into a list of tuples involves transforming each key-value pair into a tuple, where the key is the first element and the corresponding value is the second. For example, given a dictionary d = {'a': 1, 'b': 2, 'c': 3}, the expected output after conversion is [('a', 1), ('b', 2
    3 min read
  • Convert Tuples to Dictionary - Python
    The task is to convert a list of tuples into a dictionary where each tuple contains two element . The first element of each tuple becomes the key and the second element becomes the value. If a key appears multiple times its values should be grouped together, typically in a list. For example, given t
    4 min read
  • Python - Convert Binary tuple to Integer
    Given Binary Tuple representing binary representation of a number, convert to integer. Input : test_tup = (1, 1, 0) Output : 6 Explanation : 4 + 2 = 6. Input : test_tup = (1, 1, 1) Output : 7 Explanation : 4 + 2 + 1 = 7. Method #1 : Using join() + list comprehension + int() In this, we concatenate t
    5 min read
  • Python | Column Mean in tuple list
    Sometimes, while working with records, we can have a problem in which we need to average all the columns of a container of lists which are tuples. This kind of application is common in web development domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using sum() + l
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences