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 Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read