Python – flatten tuple of list to tuple

Python – Flatten tuple of List to tuple

Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have lists as its constituent elements. This kind of problem is common in data domains such as Machine Learning. Let’s discuss certain ways in which this task can be performed.

Input : test_tuple = [[5], [6], [3], [8]]
Output : [5, 6, 3, 8]

Input : test_tuple = [[5, 7, 8]]
Output : [5, 7, 8]

Method #1 : Using sum[] + tuple[]
The combination of above functions can be used to solve this problem. In this, we perform the task of flattening using sum[], passing empty list as its argument.




# Python3 code to demonstrate working of
# Flatten tuple of List to tuple
# Using sum[] + tuple[]
# initializing tuple
test_tuple = [[5, 6], [6, 7, 8, 9], [3]]
# printing original tuple
print["The original tuple : " + str[test_tuple]]
# Flatten tuple of List to tuple
# Using sum[] + tuple[]
res = tuple[sum[test_tuple, []]]
# printing result
print["The flattened tuple : " + str[res]]
Output :

The original tuple : [[5, 6], [6, 7, 8, 9], [3]] The flattened tuple : [5, 6, 6, 7, 8, 9, 3]

Method #2 : Using tuple[] + chain.from_iterable[]
The combination of above functions can be used to solve this problem. In this, we perform task of flattening using from_iterable[] and conversion to tuple using tuple[].




# Python3 code to demonstrate working of
# Flatten tuple of List to tuple
# Using tuple[] + chain.from_iterable[]
from itertools import chain
# initializing tuple
test_tuple = [[5, 6], [6, 7, 8, 9], [3]]
# printing original tuple
print["The original tuple : " + str[test_tuple]]
# Flatten tuple of List to tuple
# Using tuple[] + chain.from_iterable[]
res = tuple[chain.from_iterable[test_tuple]]
# printing result
print["The flattened tuple : " + str[res]]
Output : The original tuple : [[5, 6], [6, 7, 8, 9], [3]] The flattened tuple : [5, 6, 6, 7, 8, 9, 3]




Article Tags :
Python
Python Programs
Python tuple-programs
Read Full Article

Python program to flatten tuple of lists to a tuple

Here, we have a tuple of lists and we need to flatten it to a tuple in Python programming language.
Submitted by Shivang Yadav, on June 23, 2021

Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.

Tuples in Python is a collection of items similar to list with the difference that it is ordered and immutable.

Example:

tuple = ["python", "includehelp", 43, 54.23]

List is a sequence data type. It is mutable as its values in the list can be modified. It is a collection of ordered set of values enclosed in square brackets [].

Example:

list = [3 ,1, 5, 7]

Tuple of lists is a combination of nested collections. In which multiple lists are enclosed inside a tuple.

Example:

listTup = [[4, 1, 8], [9, 0]]

Flattening a tuple of list is converting the tuple of lists to a simple tuple containing all individual elements of the lists of the tuple.

Flatten tuple of lists to a tuple

To flatten a tuple of list to a tuple we need to put all the elements of the list in a main tuple container.

Input: [[4, 9, 1], [5 ,6]] Output: [4, 9, 1, 5, 6]

For performing this task python provides some methods. Let's explore them,

Method 1:

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.

Program:

# Python program to flatten a tuple of list to a tuple # creating the tuple of list and printing values listTup = [[4, 9, 1], [5 ,6]] print["The tuple of list : " + str[listTup]] # flattening of tuple of list flatTup = tuple[sum[listTup, []]] # Printing the flattened tuple print["Tuple after flattening : " + str[flatTup]]

Output:

The tuple of list : [[4, 9, 1], [5, 6]] Tuple after flattening : [4, 9, 1, 5, 6]

Method 2:

Another method is using a method from Python's itertools library. The chain.from_iterable[] method is used to extract single values from the tuple of a list and store them in a collection. Then we will convert this collection to tuple.

Program:

# Python program to flatten a tuple of list to a tuple from itertools import chain # creating the tuple of list and printing values listTup = [[4, 9, 1], [5 ,6]] print["The tuple of list : " + str[listTup]] # flattening of tuple of list flatTup = tuple[chain.from_iterable[listTup]] # Printing the flattened tuple print["Tuple after flattening : " + str[flatTup]]

Output:

The tuple of list : [[4, 9, 1], [5, 6]] Tuple after flattening : [4, 9, 1, 5, 6]

Python Tuple Programs »

Python program to concatenate maximum tuples
Python program to change the sign of elements of tuples in a list

ADVERTISEMENT


Preparation


Aptitude Questions MCQs Find Output Programs

What's New

  • MongoDB MCQs
  • Java MCQs
  • C# MCQs
  • Scala MCQs
  • Blockchain MCQs
  • AutoCAD MCQs
  • PHP MCQs
  • JavaScript MCQs
  • jQuery MCQs
  • ReactJS MCQs
  • AngularJS MCQs
  • JSON MCQs
  • Ajax MCQs
  • SASS MCQs
  • HTML MCQs
  • Advanced CSS MCQs
  • CSS MCQs
  • PL/SQL MCQs
  • SQL MCQs
  • MS Word MCQs
  • PL/SQL MCQs
  • SQL MCQs
  • Software Engineering MCQs
  • MIS MCQs
  • Generally Accepted Accounting Principles MCQs
  • Bills of Exchange MCQs
  • Business Environment MCQs
  • Sustainable Development MCQs
  • Marginal Costing and Absorption Costing MCQs
  • Globalisation MCQs
  • Indian Economy MCQs
  • Retained Earnings MCQs
  • Depreciation MCQs
  • Partnership MCQs
  • Sole Proprietorship MCQs
  • Goods and Services Tax [GST] MCQs
  • Cooperative Society MCQs
  • Capital Market MCQs
  • Business Studies MCQs
  • Basic Accounting MCQs
  • MIS Executive Interview Questions
  • Go Language Interview Questions
ADVERTISEMENT

Top Interview Coding Problems/Challenges!

  • Run-length encoding [find/print frequency of letters in a string]
  • Sort an array of 0's, 1's and 2's in linear time complexity
  • Checking Anagrams [check whether two string is anagrams or not]
  • Relative sorting algorithm
  • Finding subarray with given sum
  • Find the level in a binary tree with given sum K
  • Check whether a Binary Tree is BST [Binary Search Tree] or not
  • 1[0]1 Pattern Count
  • Capitalize first and last letter of each word in a line
  • Print vertical sum of a binary tree
  • Print Boundary Sum of a Binary Tree
  • Reverse a single linked list
  • Greedy Strategy to solve major algorithm problems
  • Job sequencing problem
  • Root to leaf Path Sum
  • Exit Point in a Matrix
  • Find length of loop in a linked list
  • Toppers of Class
  • Print All Nodes that don't have Sibling
  • Transform to Sum Tree
  • Shortest Source to Destination Path

Comments and Discussions!



Please enable JavaScript to view the comments powered by Disqus.
ADVERTISEMENT

How to Flatten List of Tuples in Python

There are many ways to flatten list of tuples in Python. Let us say you have the following list of tuples.

>>> a=[[1,2],[3,4],[5,6]]


1. Using sum

This is the easiest and fastest method to convert a list of tuples. We use sum function to add an empty tuple to our list of tuples. The result is a single tuple of all elements. We convert this tuple into list using list function. Please note, list function is available only in python 3+.

>>> sum[a,[]] [1, 2, 3, 4, 5, 6] >>> list[sum[a,[]]] [1, 2, 3, 4, 5, 6]# one line command >>> b=list[sum[a,[]]] >>> b [1, 2, 3, 4, 5, 6]


Flatten tuple of List to tuple in Python

PythonServer Side ProgrammingProgramming

When it is required to flatten tuple of a list to tuple, a method is defined, that takes input as tuple.

The tuple is iterated over, and the same method is called on it over and over again until the result is obtained.

Below is the demonstration of the same −

How to Convert Python Tuple to Array

Python does not have a built-in array data type like other programming languages, but if you use a library like Numpy, you will create an array.

To convert a tuple into an array:

  1. Using numpy.asarray[] method
  2. Using numpy.array[] method

5. Data Structures¶

This chapter describes some things you’ve learned about already in more detail, and adds some new things as well.

Video liên quan

Bài mới nhất

Chủ Đề