Mohamed Afzil
Mohamed Afzil

Reputation: 21

How to pass params to get required value from array of object by filtering

I am trying to build a function, which should accept the parameter and return the value by filtering an array by iterating it's value. I start to get some what looping the values.

But do not know how to declare the function and get return value from the array. not able to get some suitable online reference.

code:

lst = [["a", 45], ["b", 40], ["c", 18], ["d", 17]]

for x in range(len(lst)):
    if lst[x][0] == input("Enter your name:"):

        print("Searching in list")
        print("name:", lst[x][0], "age:", lst[x][1])

expecting:

getValue(){
findvalue = ("name:", lst[x][0], "age:", lst[x][1])
    return findvalue
}
    
value = getValue(value)

Upvotes: 2

Views: 40

Answers (1)

Lenormju
Lenormju

Reputation: 4368

What I have done :

  • store the user input in a variable (name) before the loop, so it does not ask at each iteration
  • print that we are searching in the list before the loop
  • iterate over the list items (variable item) instead of its indices
lst = [["a", 45], ["b", 40], ["c", 18], ["d", 17]]

name = input("Enter your name:")

print("Searching in list")
for item in lst:
    if item[0] == name:
        print("name:", item[0], "age:", item[1])

Upvotes: 1

Related Questions