Python – Concatenate Kth element in Tuple List
Last Updated :
07 Apr, 2023
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
test_list = [( 1 , 'Rash' , 21 ), ( 2 , 'Varsha' , 20 ), ( 3 , 'Kil' , 19 )]
print ("The original list is : " + str (test_list))
K = 1
res = " ".join([lis[K] for lis in test_list])
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
from operator import itemgetter
test_list = [( 1 , 'Rash' , 21 ), ( 2 , 'Varsha' , 20 ), ( 3 , 'Kil' , 19 )]
print ("The original list is : " + str (test_list))
K = 1
res = " ".join( list ( map (itemgetter(K), test_list)))
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
import numpy as np
test_list = [( 1 , 'Rash' , 21 ), ( 2 , 'Varsha' , 20 ), ( 3 , 'Kil' , 19 )]
print ( "The original list is: " , test_list)
K = 1
res = " " .join(np.array(test_list)[:, K])
print ( "String with only Kth tuple element (i.e names) concatenated: " , 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 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
test_list = [( 1 , 'Rash' , 21 ), ( 2 , 'Varsha' , 20 ), ( 3 , 'Kil' , 19 )]
K = 1
res = ""
for tpl in test_list:
res + = tpl[K] + " "
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:
- Import the reduce function from the functools module.
- Initialize a list of tuples called test_list.
- Initialize an integer K to 1.
- 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.
- Use the reduce function to apply the lambda function to each element of test_list and return a list of Kth elements.
- Convert the list of Kth elements to a string and join them with spaces.
- Print the resulting string.
Python3
from functools import reduce
test_list = [( 1 , 'Rash' , 21 ), ( 2 , 'Varsha' , 20 ), ( 3 , 'Kil' , 19 )]
K = 1
names = reduce ( lambda a, tpl: a + [tpl[K]], test_list, [])
res = " " .join(names)
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:
- Initialize the list of tuples test_list.
- Print the original list using the print() function and concatenation.
- Initialize the value of K.
- Use a generator expression inside the join() method to extract the Kth element (name) from each tuple in the test_list.
- Assign the result to res.
- Print the result using the print() function and concatenation
Python3
test_list = [( 1 , 'Rash' , 21 ), ( 2 , 'Varsha' , 20 ), ( 3 , 'Kil' , 19 )]
print ( "The original list is : " + str (test_list))
K = 1
res = " " .join(tup[K] for tup in test_list)
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.
Similar Reads
Python - Concatenate Rear elements in Tuple List
Given a tuple list where we need to concatenate rear elements. Input : test_list = [(1, 2, "Gfg"), ("Best", )] Output : Gfg Best Explanation : Last elements are joined. Input : test_list = [(1, 2, "Gfg")] Output : Gfg Explanation : Last elements are joined. Method #1 : Using list comprehension + joi
6 min read
Python | Concatenate two lists element-wise
In Python, concatenating two lists element-wise means merging their elements in pairs. This is useful when we need to combine data from two lists into one just like joining first names and last names to create full names. zip() function is one of the most efficient ways to combine two lists element-
3 min read
Python - Concatenate consecutive elements in Tuple
Sometimes, while working with data, we can have a problem in which we need to find cumulative results. This can be of any type, product, or summation. Here we are gonna discuss adjacent element concatenation. Letâs discuss certain ways in which this task can be performed. Method #1 : Using zip() + g
4 min read
Concatenate all Elements of a List into a String - Python
We are given a list of words and our task is to concatenate all the elements into a single string with spaces in between. For example, given the list: li = ['hello', 'geek', 'have', 'a', 'geeky', 'day'] after concatenation, the result will be: "hello geek have a geeky day". Using str.join()str.join(
3 min read
Python - Kth Column Product in Tuple List
Sometimes, while working with Python list, we can have a task in which we need to work with tuple list and get the product of itâs Kth index. This problem has application in web development domain while working with data informations. Letâs discuss certain ways in which this task can be performed. M
7 min read
Python - Add list elements to tuples list
Sometimes, while working with Python tuples, we can have a problem in which we need to add all the elements of a particular list to all tuples of a list. This kind of problem can come in domains such as web development and day-day programming. Let's discuss certain ways in which this task can be don
6 min read
Python | Record elements Average in List
Given a list of tuples, write a program to find average of similar tuples in list. Examples: Input: [('Geeks', 10), ('For', 10), ('Geeks', 2), ('For', 9), ('Geeks', 10)] Output: Resultant list of tuples: [('For', 9.5), ('Geeks', 7.333333333333333)] Input: [('Akshat', 10), ('Garg', 10), ('Akshat', 2)
3 min read
Python | Concatenate dictionary value lists
Sometimes, while working with dictionaries, we might have a problem in which we have lists as it's value and wish to have it cumulatively in single list by concatenation. This problem can occur in web development domain. Let's discuss certain ways in which this task can be performed. Method #1 : Usi
5 min read
Python | Adding N to Kth tuple element
Many times, while working with records, we can have a problem in which we need to change the value of tuple elements. This is a common problem while working with tuples. Let's discuss certain ways in which N can be added to Kth element of tuple in list. Method #1 : Using loop Using loops this task c
3 min read
Repeat Each Element K times in List - Python
The task of repeating each element k times in a list in Python involves creating a new list where each element from the original list appears k times consecutively. For example, given the list a = [4, 5, 6] and k = 3, the goal is to produce [4, 4, 4, 5, 5, 5, 6, 6, 6]. Using list comprehensionList c
3 min read