How to Concatenate Tuples to Nested TuplesThis 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 "," operatorWe 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 concatenationLet'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() methodsLet'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 tuplesSometimes, 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 comprehensionWe 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 + tupleIn 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)]] ConclusionIn 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. |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India