Open In App
Related Articles

Python – Concatenate Kth element in Tuple List

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

While working with tuples, we store different data as different tuple elements. Sometimes, there is a need to print a specific information from the tuple. For instance, a piece of code would want just names to be printed of all the student data in concatenated format. Lets discuss certain ways how one can achieve solutions to this problem. 

Method #1 : Using list comprehension + join() List comprehension is the simplest way in which this problem can be solved. We can just iterate over only the specific index value in all the index and store it in a list and concat it after that using join(). 

Python3

# Python3 code to demonstrate
# Concatenating Kth element in Tuple List
# using list comprehension
 
# initializing list of tuples
test_list = [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# initializing K
K = 1
 
# using list comprehension + join() to concatenate names
res = " ".join([lis[K] for lis in test_list])
     
# printing result
print ("String with only Kth tuple element (i.e names) concatenated : " + str(res))

                    
Output : 
The original list is : [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)]
String with only Kth tuple element (i.e names) concatenated : Rash Varsha Kil

Time complexity of the code is O(n), where n is the length of the list of tuples. 

The auxiliary space complexity of the code is also O(n), as the list comprehension creates a new list of length n to store the Kth element of each tuple.

 Method #2 : Using map() + itemgetter() + join() map() coupled with itemgetter() can perform this task in more simpler way. map() maps all the element we access using itemgetter() and returns the result. The task of concatenation is performed using join(). 

Python3

# Python3 code to demonstrate
# Concatenating Kth element in Tuple List
# using map() + itergetter() + join()
from operator import itemgetter
 
# initializing list of tuples
test_list = [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# initializing K
K = 1
 
# using map() + itergetter() + join() to get names
res = " ".join(list(map(itemgetter(K), test_list)))
     
# printing result
print ("String with only nth tuple element (i.e names) concatenated : " + str(res))

                    
Output : 
The original list is : [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)]
String with only Kth tuple element (i.e names) concatenated : Rash Varsha Kil

The time complexity of the provided code is O(n), where n is the length of the input tuple list.

The auxiliary space of the provided code is O(n), where n is the length of the input tuple list.

Method #3 : Using numpy

This approach uses the numpy library to extract the Kth element from each tuple in the list and concatenate the result. The np.array function is used to convert the list of tuples into a numpy array, and the [:, K] indexing syntax is used to extract the Kth element from each tuple. Finally, the join method is used to concatenate the extracted elements into a single string. The time complexity of this approach is O(n) and the space complexity is O(n), where n is the number of tuples in the list.

Note: Install numpy module using command “pip install numpy”

Python3

# Using numpy to concatenate Kth element in Tuple List
 
import numpy as np
 
# initializing list of tuples
test_list = [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)]
 
# printing original list
print("The original list is: ", test_list)
 
# initializing K
K = 1
 
# Using numpy to extract Kth element in Tuple List
res = " ".join(np.array(test_list)[:, K])
 
# printing result
print("String with only Kth tuple element (i.e names) concatenated: ", res)
#This code is contributed by Edula Vinay Kumar Reddy

                    

Output:

The original list is:  [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)]
String with only Kth tuple element (i.e names) concatenated:  Rash Varsha Kil

Time Complexity: O(N), where N is the number of tuples in test_list. 

Auxiliary Space: O(N), where N is the number of tuples in test_list. 

Method #4: Using a for loop to extract the Kth element and join the strings.

Initializes a list of tuples and extracts the second element (K=1) from each tuple using a for loop. The extracted elements are concatenated into a string with a space separator and printed.

Python3

# initializing list of tuples
test_list = [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)]
 
# initializing K
K = 1
 
# Using for loop to extract Kth element in Tuple List
res = ""
for tpl in test_list:
    res += tpl[K] + " "
 
# printing result
print("String with only Kth tuple element (i.e names) concatenated: ", res)

                    

Output
String with only Kth tuple element (i.e names) concatenated:  Rash Varsha Kil 

Time Complexity: O(n), where n is the number of tuples in the list.

Space Complexity: O(n), where n is the number of tuples in the list.

Method 5: Using the reduce() function from the functools module and a lambda function.

Algorithm:

  1. Import the reduce function from the functools module.
  2. Initialize a list of tuples called test_list.
  3. Initialize an integer K to 1.
  4. Define a lambda function that takes two arguments: a and tpl. The lambda function extracts the Kth element of tpl and appends it to a.
  5. Use the reduce function to apply the lambda function to each element of test_list and return a list of Kth elements.
  6. Convert the list of Kth elements to a string and join them with spaces.
  7. Print the resulting string.

Python3

from functools import reduce
 
 
# initializing list of tuples
test_list = [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)]
 
# initializing K
K = 1
 
names = reduce(lambda a, tpl: a + [tpl[K]], test_list, [])
res = " ".join(names)
 
# printing result
print("String with only Kth tuple element (i.e names) concatenated: ", res)

                    

Output
String with only Kth tuple element (i.e names) concatenated:  Rash Varsha Kil

Time complexity:

The lambda function inside reduce is executed for each element in test_list, so its time complexity is O(1).
The reduce function iterates through each element in test_list and applies the lambda function to it, so its time complexity is O(n).
The join function joins the list of names with spaces, so its time complexity is O(n).
Therefore, the overall time complexity of the code is O(n), where n is the number of tuples in test_list.

Space complexity:

The size of the list of tuples test_list is O(n), where n is the number of tuples in the list.
The integer variable K occupies a constant amount of space, so its space complexity is O(1).
The reduce function stores the result of the lambda function in a list. The size of the list is also O(n), so the space complexity of the reduce function is O(n).
The lambda function creates a list to store the extracted Kth element for each tuple, so the space complexity of the lambda function is also O(n).
The join function creates a new string, which has a space complexity of O(n).
The names list created in reduce is discarded after it’s converted to a string, so it doesn’t contribute to the overall space complexity.
Therefore, the overall space complexity of the code is O(n), where n is the number of tuples in test_list.

Method #6: Using a generator expression and join()

Step-by-step approach:

  1. Initialize the list of tuples test_list.
  2. Print the original list using the print() function and concatenation.
  3. Initialize the value of K.
  4. Use a generator expression inside the join() method to extract the Kth element (name) from each tuple in the test_list.
  5. Assign the result to res.
  6. Print the result using the print() function and concatenation

Python3

# Python3 code to demonstrate
# Concatenating Kth element in Tuple List
# using generator expression and join()
 
# initializing list of tuples
test_list = [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 1
 
# using generator expression and join() to concatenate names
res = " ".join(tup[K] for tup in test_list)
 
# printing result
print("String with only Kth tuple element (i.e names) concatenated : " + str(res))

                    

Output
The original list is : [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)]
String with only Kth tuple element (i.e names) concatenated : Rash Varsha Kil

Time complexity: O(n), where n is the number of tuples in the test_list.
Auxiliary space: O(1), as no additional space is used other than the input test_list and the output string res.



Last Updated : 07 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads