Javatpoint Logo
Javatpoint Logo

How to Concatenate Tuples to Nested Tuples

This tutorial will teach us how to concatenate tuples into nested ones. Sometimes, we need to convert the individual records into a nested collection yet found as a separate element. In other words, we will add the tuples and flattens the resultant container; it is usually undesirable. We will discuss the various methods to perform this task.

Method - 1: Using + operator and "," operator

We will add tuple elements and initialize the tuple using the comma after the tuple so that they don't get flattened during addition. Let's understand the following example.

Example -

Output:

The original tuple 1 : ((1, 2),)
The original tuple 2 : ((3, 4),)
Tuples after Concatenating : ((1, 2), (3, 4))

Method: 2 - Using ", " operator during concatenation

Let's understand the following example.

Example -

Output:

The original tuple 1 : ((1, 2),)
The original tuple 2 : ((3, 4),)
Tuples after Concatenating : (((1, 2),), ((3, 4),))

Method - 3: Using list(), extend() and tuple() methods

Let's understand the following example -

Example -

Output:

The original tuple 1 : ((1, 2),)
The original tuple 2 : ((3, 4),)
Tuples after Concatenating: ((1, 2), (3, 4))

How to convert nested sublist into tuples

Sometimes, we have a massive amount of data, and we might have in which each point of data establishes various elements and requires to be processed as a single unit. For example, we might receive a matrix whose primary data points are lists, which don't seem reasonable and might be required to be converted to tuples. Let's understand the various methods to convert the sublist into tuples.

Method - 1: Using tuple() + list comprehension

We can do this using a single line of code to solve this problem. We will iterate through the innermost sublist and convert each of the lists of the tuple using tuple(). Let's understand the following example.

Example -

Output:

The original list is : [[[1, 2, 3], [4, 6, 7]], [[6, 9, 8], [10, 11, 12]]]
The list conversion to tuple is : [[(1, 2, 3), (4, 6, 7)], [(6, 9, 8), (10, 11, 12)]]

Method - 2: Using map() + list comprehension + tuple

In this method, we use the map() function in place of the inner loop to tuple conversion to each element. Let's understand the following example.

Example -

Output:

The original list is : [[[1, 2, 3], [4, 6, 7]], [[6, 9, 8], [10, 11, 12]]]
The list conversion to tuple is : [[(1, 2, 3), (4, 6, 7)], [(6, 9, 8), (10, 11, 12)]]

Conclusion

In this tutorial, we discussed concatenating tuples into nested tuples and converting the nested sublist in the list. We have used various methods along with the example.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA