Python | Selective value selection in list of tuples
Last Updated :
02 May, 2023
Sometimes, while using list of tuples, we come across a problem in which we have a certain list of keys and we just need the value of those keys from list of tuples. This has a utility in rating or summation of specific entities. Let's discuss certain ways in which this can be done.
Method #1 : Using dict() + get() + list comprehension
We can perform this particular task by first, converting the list into the dictionary and then employing list comprehension to get the value of specific keys using get function.
Python3
# Python3 code to demonstrate
# Selective Value selection in list of tuples
# using dict() + get() + list comprehension
# initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
# initializing selection list
select_list = ['Nikhil', 'Akshat']
# printing original list
print("The original list is : " + str(test_list))
# printing selection list
print("The selection list is : " + str(select_list))
# using dict() + get() + list comprehension
# Selective Value selection in list of tuples
temp = dict(test_list)
res = [temp.get(i, 0) for i in select_list]
# printing result
print("The selective values of keys : " + str(res))
OutputThe original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values of keys : [1, 3]
Time Complexity: O(n), where n is the length of the test_list.
Auxiliary Space: O(n), where n is the length of the test_list.
Method #2: Using next() + list comprehension
This particular problem can be solved using the next function which performs the iteration using the iterators and hence more efficient way to achieve a possible solution.
Python3
# Python3 code to demonstrate
# Selective Value selection in list of tuples
# using next() + list comprehension
# initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
# initializing selection list
select_list = ['Nikhil', 'Akshat']
# printing original list
print("The original list is : " + str(test_list))
# printing selection list
print("The selection list is : " + str(select_list))
# using next() + list comprehension
# Selective Value selection in list of tuples
res = [next((sub[1] for sub in test_list
if sub[0] == i), 0) for i in select_list]
# printing result
print("The selective values of keys : " + str(res))
OutputThe original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values of keys : [1, 3]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3 : Using for loop
Python3
# Python3 code to demonstrate
# Selective Value selection in list of tuples
# initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
# initializing selection list
select_list = ['Nikhil', 'Akshat']
# printing original list
print("The original list is : " + str(test_list))
# printing selection list
print("The selection list is : " + str(select_list))
res = []
for i in select_list:
for j in range(0, len(test_list)):
if(test_list[j][0] == i):
res.append(test_list[j][1])
# printing result
print("The selective values of keys : " + str(res))
OutputThe original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values of keys : [1, 3]
Time complexity: O(n * m), where n is the length of the select_list and m is the length of the test_list.
Auxiliary space: O(k), where k is the length of the res list.
Method #4 : Using list comprehension without dict()
Here is an example of how you can use list comprehension to selectively select values from a list of tuples:
Python3
# Initialize the list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
# Initialize the selection list
select_list = ['Nikhil', 'Akshat']
# Selectively select the values using list comprehension
res = [tuple[1] for tuple in test_list if tuple[0] in select_list]
print(res) # Output: [1, 3]
# This code is contributed by Edula Vinay Kumar Reddy
Time complexity: O(n), where n is the number of tuples in the test_list.
Auxiliary space: O(m), where m is the number of selected names in the select_list.
Method #5: Using filter() + map() function
- Initialize the list of tuples
- Initialize the selection list
- Define a lambda function that takes in a tuple and returns True if the first element of the tuple is in the selection list, otherwise False
- Use the filter() function to create a new list of tuples that match the selection criteria
- Use the map() function to extract the second element of each tuple in the filtered list
- Convert the map object to a list
- Print the resulting list of values
Python3
# initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
# initializing selection list
select_list = ['Nikhil', 'Akshat']
# printing original list
print("The original list is : " + str(test_list))
# printing selection list
print("The selection list is : " + str(select_list))
# using filter() + map() function
# Selective Value selection in list of tuples
res = list(map(lambda x: x[1], filter(lambda x: x[0] in select_list, test_list)))
# printing result
print("The selective values of keys : " + str(res))
OutputThe original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values of keys : [1, 3]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #6: Using a dictionary comprehension
Create a dictionary comprehension that filters the original list of tuples by checking if the first element of each tuple is in the selection list, and returns a dictionary with keys equal to the first element of the tuples and values equal to the second element of the tuples.
Use a list comprehension to create a list of values from the resulting dictionary.
Python3
# Python3 code to demonstrate
# Selective Value selection in list of tuples
# using a dictionary comprehension
# initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
# initializing selection list
select_list = ['Nikhil', 'Akshat']
# printing original list
print("The original list is : " + str(test_list))
# printing selection list
print("The selection list is : " + str(select_list))
# using a dictionary comprehension
# Selective Value selection in list of tuples
res_dict = {k: v for k, v in test_list if k in select_list}
res = [res_dict[k] for k in select_list]
# printing result
print("The selective values of keys : " + str(res))
OutputThe original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values of keys : [1, 3]
Time complexity: O(n)
Auxiliary space: O(n)
Approach using Numpy:
Note: Install numpy module using command "pip install numpy"
Algorithm:
Convert the list of tuples into a NumPy array.
Extract the first and second columns of the array separately as two 1D arrays.
Use np.where() function to get the indices where the first column matches the values in select_list.
Use the above indices to get the corresponding values from the second array.
Return the resulting array.
Python3
import numpy as np
# initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
# initializing selection list
select_list = ['Nikhil', 'Akshat']
# printing original list
print("The original list is : " + str(test_list))
# printing selection list
print("The selection list is : " + str(select_list))
# converting the list of tuples to a NumPy array
arr = np.array(test_list)
# extracting the first and second columns separately
col1 = arr[:, 0]
col2 = arr[:, 1]
# getting the indices where the first column matches the values in select_list
indices = np.where(np.isin(col1, select_list))
# using the indices to get the corresponding values from the second column
res = list(map(int,col2[indices]))
# printing the resulting array
print("The selective values of keys : " + str(list(res)))
Output:
The original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values of keys : [1, 3]
Time Complexity: O(n), where n is the length of the test_list.
Auxiliary Space: O(n), where n is the length of the test_list.
Note: The time complexity of the NumPy solution is the same as the dict() solution, but it may have better performance due to NumPy's efficient array operations.
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â 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.Python is:A high-level language, used in web development, data science, automatio
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 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
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
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
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