Q:

Python | Records with Value at K index

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Getting Records with Value at K index

In this program, we are given a list of tuples and two integer value elements, and index k. We will be creating a python program to get records with value at k index.

Input:
[(5, 7), (4, 8, 3, 1), (5, 8, 0), (1, 2, 3, 4, 5, 7)] 
ele = 8, k = 2

Output:
[(4, 8, 3, 1), (5, 8, 0)]

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One method to solve the problem is by using a direct approach where we will traverse the list and check if the given element is present at the specific index k.

# Program to get records with Value 
# at K index using loop,
  
# intializing and printing the tupleList, 
tupList = [(5, 7, 1), (4, 8, 3), (5, 8, 0), (1, 2, 3)]
print("Initial values of the tuple list are " + str(tupList))
  
ele = 8
K = 1

# filtering records with element at k index using loop  
filterList = []
for x, y, z in tupList:
    if y == ele:
        filterList.append((x, y, z))
  
print("The tuples from the list with given element at Kth index is " + str(filterList))

Output:

Initial values of the tuple list are [(5, 7, 1), (4, 8, 3), (5, 8, 0), (1, 2, 3)]
The tuples from the list with given element at Kth index is [(4, 8, 3), (5, 8, 0)]

Method 2:

Another method to solve the problem is by enumeration of indexes and then comparing the element for the given index. To perform the task in a single line of code, we will be using list comprehension.

# Program to get records with Value 
# at K index using loop,
  
# intializing and printing the tupleList, 
tupList = [(5, 7, 1), (4, 8, 3), (5, 8, 0), (1, 2, 3)]
print("Initial values of the tuple list are " + str(tupList))
  
ele = 8
K = 1

# filtering records with element at k index using loop  
filterList = [b for a, b in enumerate(tupList) if b[K] == ele]

print("The tuples from the list with given element at Kth index is " + str(filterList))

Output:

Initial values of the tuple list are [(5, 7, 1), (4, 8, 3), (5, 8, 0), (1, 2, 3)]
The tuples from the list with given element at Kth index is [(4, 8, 3), (5, 8, 0)]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now