How do you convert a list into a list of tuples?

OR

>>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"] >>> [i for i in zip[*[iter[L]]*2]] [[1, 'term1'], [3, 'term2'], [4, 'term3'], [5, 'termN']]

OR

>>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"] >>> map[None,*[iter[L]]*2] [[1, 'term1'], [3, 'term2'], [4, 'term3'], [5, 'termN']] >>>

Method 1: List Comprehension + tuple[]

Problem: How to convert a list of lists into a list of tuples?

Example: You’ve got a list of lists [[1, 2], [3, 4], [5, 6]] and you want to convert it into a list of tuples [[1, 2], [3, 4], [5, 6]].

Solution: There are different solutions to convert a list of lists to a list of tuples. Use list comprehension in its most basic form:

lst = [[1, 2], [3, 4], [5, 6]] tuples = [tuple[x] for x in lst] print[tuples] # [[1, 2], [3, 4], [5, 6]]

Try It Yourself:

This approach is simple and effective. List comprehension defines how to convert each value [x in the example] to a new list element. As each list element is a new tuple, you use the constructor tuple[x] to create a new tuple from the list x.

If you have three list elements per sublist, you can use the same approach with the conversion:

lst = [[1, 2, 1], [3, 4, 3], [5, 6, 5]] tuples = [tuple[x] for x in lst] print[tuples] # [[1, 2, 1], [3, 4, 3], [5, 6, 5]]

You can see the execution flow in the following interactive visualization [just click the “Next” button to see what’s happening in the code]:

And if you have a varying number of list elements per sublist, this approach still works beautifully:

lst = [[1], [2, 3, 4], [5, 6, 7, 8]] tuples = [tuple[x] for x in lst] print[tuples] # [[1,], [2, 3, 4], [5, 6, 7, 8]]

You see that an approach with list comprehension is the best way to convert a list of lists to a list of tuples. But are there any alternatives?

Python | Convert a list into a tuple

Given a list, write a Python program to convert the given list into a tuple.

Examples:

Input : [1, 2, 3, 4] Output : [1, 2, 3, 4] Input : ['a', 'b', 'c'] Output : ['a', 'b', 'c']


Approach #1 : Using tuple[list_name].

Typecasting to tuple can be done by simply using tuple[list_name].




# Python3 program to convert a

# list into a tuple

def convert[list]:

return tuple[list]

# Driver function

list = [1, 2, 3, 4]

print[convert[list]]

Output:


[1, 2, 3, 4]


Approach #2 :
A small variation to the above approach is to use a loop inside tuple[] .




# Python3 program to convert a

# list into a tuple

def convert[list]:

return tuple[i for i in list]

# Driver function

list = [1, 2, 3, 4]

print[convert[list]]

Output: [1, 2, 3, 4]


Approach #3 : Using [*list, ]
This essentially unpacks the list l inside a tuple literal which is created due to the presence of the single comma [, ]. This approach is a bit faster but suffers from readability.




# Python3 program to convert a

# list into a tuple

def convert[list]:

return [*list, ]

# Driver function

list = [1, 2, 3, 4]

print[convert[list]]

Output: [1, 2, 3, 4]




Article Tags :

Python

Python Programs

Python list-programs

Python tuple-programs

python-list

python-tuple

Practice Tags :

python-list

Read Full Article

Python – Convert List of Lists to Tuple of Tuples

Sometimes, while working with Python data, we can have a problem in which we need to perform interconversion of data types. This kind of problem can occur in domains in which we need to get data in particular formats such as Machine Learning. Let’s discuss certain ways in which this task can be performed.

Input : test_list = [[‘Best’], [‘Gfg’], [‘Gfg’]]
Output : [[‘Best’, ], [‘Gfg’, ], [‘Gfg’, ]]

Input : test_list = [[‘Gfg’, ‘is’, ‘Best’]]
Output : [[‘Gfg’, ‘is’, ‘Best’], ]

Method #1 : Using tuple[] + list comprehension
The combination of above functions can be used to solve this problem. In this, we perform the conversion using tuple[] and list comprehension is used to extend logic to all the containers.




# Python3 code to demonstrate working of

# Convert List of Lists to Tuple of Tuples

# Using tuple + list comprehension

# initializing list

test_list = [['Gfg', 'is', 'Best'], ['Gfg', 'is', 'love'],

['Gfg', 'is', 'for', 'Geeks']]

# printing original list

print["The original list is : " + str[test_list]]

# Convert List of Lists to Tuple of Tuples

# Using tuple + list comprehension

res = tuple[tuple[sub] for sub in test_list]

# printing result

print["The converted data : " + str[res]]

Output :


The original list is : [[‘Gfg’, ‘is’, ‘Best’], [‘Gfg’, ‘is’, ‘love’], [‘Gfg’, ‘is’, ‘for’, ‘Geeks’]]
The converted data : [[‘Gfg’, ‘is’, ‘Best’], [‘Gfg’, ‘is’, ‘love’], [‘Gfg’, ‘is’, ‘for’, ‘Geeks’]]

Method #2 : Using map[] + tuple[]
The combination of above functions can be used to solve this problem. In this, we perform the task performed using list comprehension using map[], to extend the conversion logic to each sublist.




# Python3 code to demonstrate working of

# Convert List of Lists to Tuple of Tuples

# Using map[] + tuple[]

# initializing list

test_list = [['Gfg', 'is', 'Best'], ['Gfg', 'is', 'love'],

['Gfg', 'is', 'for', 'Geeks']]

# printing original list

print["The original list is : " + str[test_list]]

# Convert List of Lists to Tuple of Tuples

# Using map[] + tuple[]

res = tuple[map[tuple, test_list]]

# printing result

print["The converted data : " + str[res]]

Output :

The original list is : [[‘Gfg’, ‘is’, ‘Best’], [‘Gfg’, ‘is’, ‘love’], [‘Gfg’, ‘is’, ‘for’, ‘Geeks’]]
The converted data : [[‘Gfg’, ‘is’, ‘Best’], [‘Gfg’, ‘is’, ‘love’], [‘Gfg’, ‘is’, ‘for’, ‘Geeks’]]




Article Tags :

Python

Python Programs

Python list-programs

Python tuple-programs

Read Full Article

Python List list[] Method

Advertisements


Previous Page

Next Page

Python Exercise: Convert a list to a tuple

Last update on January 29 2021 07:13:37 [UTC/GMT +8 hours]

How to Convert a List into a Tuple in Python

June 27, 2021October 10, 2021 0 Comments convert list to tuple, how to convert a list into a tuple in python

In this tutorial, we are going to see how to convert List into a Tuple in Python. Python provides different types of variables for programmers. We can use data types like int, float, string, list, set… in our applications. When using different types of variables, it may be necessary to convert these to different types.

How to Convert a List into a Tuple in Python# List of integers nbr_liste = [1, 2, 3, 4, 5, 6] print[nbr_liste] # Convert list to tuple nbr_tuple = tuple[nbr_liste] # Print the tuple print[nbr_tuple]

Output:

[1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6]
MCQPractice competitive and technical Multiple Choice Questions and Answers [MCQs] with simple and logical explanations to prepare for tests and interviews. Spread the loveRead More

  • Button Tkinter | Python 3
  • Label Tkinter | Python 3
  • Text Tkinter | Python 3
  • Entry Tkinter | Python 3
  • Message Tkinter | Python 3
  • Checkbutton Tkinter | Python 3
  • Radiobutton Tkinter | Python 3
  • Menu Tkinter | Python 3
  • Menubutton Tkinter | Python 3
  • Frame Tkinter | Python 3
  • Scrollbar Tkinter | Python 3
  • Spinbox Tkinter | Python 3
  • Listbox Tkinter | Python 3
  • Canvas Tkinter | Python 3
  • tkMessageBox Tkinter | Python 3
  • LabelFrame Tkinter | Python 3
  • Scale Tkinter | Python 3
  • Toplevel Tkinter | Python 3
  • PanedWindow Tkinter | Python 3
  • pack[] Method in Tkinter Python 3
  • grid[] Method in Tkinter Python 3
  • place[] Method in Tkinter Python 3
  • How to Get Window Size in Tkinter Python
  • How to Set Default Tkinter Entry Value in Python
  • How to Change the Default Icon on a Tkinter Window
  • How to Bind The Enter key to a Function in Tkinter
  • How to Clear Text From a Text Widget on Click in Tkinter
  • How to Set The Width and Height of a Tkinter Entry
  • How to Get the Input From the Tkinter Text Widget
  • How to Make Tkinter Text Widget Read Only
  • How to Increase Font Size in Text Widget in Tkinter
  • How to Get the Tkinter Label Text
  • How To Show/Hide a Label in Tkinter After Pressing a Button
  • How to Delete Tkinter Button After Click
  • How to Change Label Text on Button Click in Tkinter
  • How to Change the Font Size in a Label in Tkinter Python
  • How to Make a Timer in Python Tkinter
  • How To Display a Tkinter Window in Fullscreen
  • How to Stop a Tkinter Window From Resizing
  • How to Open a New Window With a Button in Python Tkinter
  • How to Disable/Enable Tkinter Button in Python
  • How to Close a Tkinter Window With a Button
  • How to Pass Arguments to Tkinter button’s callback Command?
  • How to Bind Multiple Commands to Tkinter Button
  • How to Change Background Color of the Window in Tkinter Python
  • How to Change Background Color of a Tkinter Button in Python
  • How to Change Text of Button When Clicked in Tkinter Python
  • How to change font and size of buttons in Tkinter Python
  • How to Set Tkinter Window Size – Python
  • How To Add Image To Button In Python Tkinter
  • How to run a python script from the command line in Windows 10
  • How to install Python on Windows
  • How to Install Pip for Python on Windows
  • Python Program to Check a Number or String is Palindrome
  • Palindrome Program In Python Using Recursion
  • What is Django used for?
  • Python – Generate a Random Alphanumeric String
  • How to generate a random number in Python
  • Python – Check if Variable is a Number
  • Python Program to Check Armstrong Number
  • Python Program to Check if a Year is a Leap Year
  • Python program to convert decimal to binary
  • Check if a number is odd or even in Python
  • Factorial in Python
  • Factorial of a Number Using Recursion in Python
  • Selection Sort in Python
  • Insertion Sort in Python
  • Bubble Sort in Python
  • How to check if a list is empty in Python
  • How to Count Occurrences of Each Character in String – Python
  • Python – Read a file line-by-line
  • How to get the path of the current directory in Python
  • How to get file creation and modification date in Python
  • How to extract a zip file in Python
  • How to Recursively Remove a Directory in Python
  • How to check if a file or a directory exists in Python
  • How to move a file or directory in Python
  • How to create a directory in Python
  • How to list all the files in a directory in Python
  • How to delete a file or directory in Python
  • How to check if a directory is empty in Python
  • Python – How to copy files from one directory to another
  • How to Create Nested Dictionary in Python
  • How to add keys and values to a dictionary in Python
  • How to copy a dictionary in Python
  • How to get key by value in dictionary in Python
  • Python – Check if String Contains Substring
  • Python – Remove duplicates from a list
  • How to Remove More Than One Element From List in Python
  • Python – Convert a Tuple to a String
  • Python – Convert list of tuples to list of lists
  • Python – Convert a list of tuples into list
  • How to Convert a List into a Tuple in Python
  • How to Convert a String to Float in Python
  • How to Convert a String to an integer in Python
  • How To Convert String To List in Python
  • How to Convert List to String in Python
  • How to Sort a Dictionary by Value in Python
  • How to Sort a Dictionary by Key in Python
  • How to Check if an Item Exists in a List in Python
  • Python – Check if all elements in a List are the same
  • How to merge two lists in Python
  • Python – How to Insert an element at a specific index in List
  • Python Check If a List Contains Elements of Another List
  • Write a Program to Print the Sum of Two Numbers in Python
  • How to convert a list of key-value pairs to dictionary Python
  • Fibonacci Series in Python using Recursion
  • Fibonacci Series in Python using While Loop
  • Python Program to Display Prime Numbers in a Given Range
  • Python MCQ and Answers – Part 1
  • Python MCQ and Answers – Part 2
  • Python MCQ and Answers – Part 3
  • Python MCQ and Answers – Part 4
  • Python MCQ and Answers – Part 5
  • Python MCQ and Answers – Part 6
  • Python MCQ and Answers – Part 7
  • Python MCQ and Answers – Part 8
  • Python MCQ and Answers – Part 9
  • Python MCQ and Answers – Part 10
  • Python MCQ and Answers – Part 11
  • Python MCQ and Answers – Part 12
  • Python MCQ and Answers – Part 13
  • Python MCQ and Answers – Part 14
  • Python MCQ and Answers – Part 15
  • Python MCQ and Answers – Part 16
  • Python MCQ and Answers – Part 17
  • Python MCQ and Answers – Part 18
  • Python MCQ and Answers – Part 19
  • Python MCQ and Answers – Part 20
  • Lists in Python
  • String Functions and Methods in Python
  • Using Variables In Python
  • Output using print[] function in Python
  • Python MCQ and Answers – Lists
  • Python MCQ and Answers – Strings
  • Python MCQ and Answers – Data types
  • Python MCQ and Answers – Variables And Operators – Part 2
  • Python MCQ and Answers – Variables And Operators – Part 1

Spread the love

Video liên quan

Bài mới nhất

Chủ Đề