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
# 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)
OutputString 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
# 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)
OutputString 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
# 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))
OutputThe 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 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()
2 min read
Python - Alternate Elements operation on Tuple
Sometimes, while working with Python Tuples, we can have problem in which we need to perform operations of extracted alternate chains of tuples. This kind of operation can have application in many domains such as web development. Lets discuss certain ways in which this task can be performed. Input :
5 min read
Update Each Element in Tuple List - Python
The task of updating each element in a tuple list in Python involves adding a specific value to every element within each tuple in a list of tuples. This is commonly needed when adjusting numerical data stored in a structured format like tuples inside lists. For example, given a = [(1, 3, 4), (2, 4,
3 min read
Python - Concatenate Tuple elements by delimiter
Given a tuple, concatenate each element of tuple by delimiter. Input : test_tup = ("Gfg", "is", 4, "Best"), delim = ", " Output : Gfg, is, 4, Best Explanation : Elements joined by ", ". Input : test_tup = ("Gfg", "is", 4), delim = ", " Output : Gfg, is, 4 Explanation : Elements joined by ", ". Metho
7 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 - Consecutive K elements join in List
Sometimes, while working with Python lists, we can have a problem in which we need to join every K character into one collection. This type of application can have use cases in many domains like day-day and competitive programming. Let us discuss certain ways in which this task can be performed. Met
4 min read
Python | Concatenate N consecutive elements in String list
Sometimes, while working with data, we can have a problem in which we need to perform the concatenation of N consecutive Strings in a list of Strings. This can have many applications across domains. Let's discuss certain ways in which this task can be performed. Method #1: Using format() + zip() + i
8 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