Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten a tuple in python

Tags:

I have the following element of a list, and the list is 100 elements long.

[(50, (2.7387451803816479e-13, 219))] 

How do I convert each element to look like this?

[(50, 2.7387451803816479e-13, 219)] 
like image 798
olliepower Avatar asked Aug 29 '13 00:08

olliepower


People also ask

How do you flatten a tuple list in Python?

One method to flatten tuples of a list is by using the sum() method with empty lust which will return all elements of the tuple as individual values in the list. Then we will convert it into a tuple. Method 2: Another method is using a method from Python's itertools library.

How do you flatten a nested tuple?

Flattening Nested Tuples To solve the problem is by finding all the nested tuples in each tuple element of the container. And then flatten it to a normal tuple with all elements of the nested as individual elements.

How do you unpack a tuple?

Python uses a special syntax to pass optional arguments (*args) for tuple unpacking. This means that there can be many number of arguments in place of (*args) in python. All values will be assigned to every variable on the left-hand side and all remaining values will be assigned to *args .

What is flatten list Python?

Flattening a list of lists entails converting a 2D list into a 1D list by un-nesting each list item stored in the list of lists - i.e., converting [[1, 2, 3], [4, 5, 6], [7, 8, 9]] into [1, 2, 3, 4, 5, 6, 7, 8, 9] .


2 Answers

[(a, b, c) for a, (b, c) in l] 

Tuple packing and unpacking solves the problem.

like image 53
user2357112 supports Monica Avatar answered Oct 13 '22 00:10

user2357112 supports Monica


New in Python 3.5 with the additional tuple unpacking introduced in PEP 448, you can use starred expressions in tuple literals such that you can use

>>> l = [(50, (2.7387451803816479e-13, 219)), (40, (3.4587451803816479e-13, 220))] >>> [(a, *rest) for a, rest in l] [(50, 2.738745180381648e-13, 219), (40, 3.458745180381648e-13, 220)] 

This could be useful if you had a nested tuple used for record-keeping with many elements that you wanted to flatten.

like image 35
miradulo Avatar answered Oct 12 '22 23:10

miradulo