Sololearn: Learn to Code
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1
if you want to iterate with i as index of the tuple list, you must iterate it over a range object... for i in range(len(contacts)): # contacts[i] is the (i+1)th item by iterating over contacts, you will get each item of the list: for t in contacts: # t is each tuple from the tuples, you can access each value by using square brackets notation as for lists... for t in contacts: # t[0] is the name (string) # t[1] is the age (number) or unpack the tuple while iterating... for n, a in contacts: # n is the name # a is the age then to find the tuple with 'name' and get its age: answer = None for n, a in contacts: if (n == name): answer = a break # exit the loop as we have found name then we can output the result: if answer is None: print("Not found") else: print(name,"is",age) there could be make a lot of improvements, but that's another topic ;) hope this help! :)
25th Mar 2021, 2:16 PM
visph
visph - avatar
0
Convert the tuple to a dictionary.
25th Mar 2021, 2:00 PM
Jan
Jan - avatar
0
It's much more convenient to do this... dt = dict(contacts) Then you can easily access the values by the key.
25th Mar 2021, 2:24 PM
Jan
Jan - avatar
0
Charlie DCH --> I think you meant - why would I use a dictionary instead. It reduces the lines of code when converting the tuple to a dictionary and then you have easy access to retrieve the values by the key. Python is quite smooth in many ways.
25th Mar 2021, 7:41 PM
Jan
Jan - avatar
0
Charlie DSC --> You need an if else statement like this... if name in dt: print(name + " is " + str(dt.get(name))) else: print("Not found")
27th Mar 2021, 3:04 PM
Jan
Jan - avatar