+ 1

Crossing list elements, what the best method for you ?

names = ["name 1", "name 2", "name 3", "name4"] ages = ["12", "18", "22", "5", "60"] #with the zip function for i in zip(names, ages): print("name : {} - age : {} years old".format(i[0], i[1])) #with the enumerate function for i, n in enumerate(names): print("name : {} - age : {} years old".format(n, ages[i]))

20th Jul 2018, 8:36 PM
DDD
DDD - avatar
5 Réponses
+ 4
yes
21st Jul 2018, 10:32 AM
John Wells
John Wells - avatar
+ 3
I'd do: for n, a in zip(names, ages): print("name : {} - age : {} years old".format(n, a)) It handles lists of different lengths correctly. The enumerate fails as coded, when ages is shorter than names.
20th Jul 2018, 10:26 PM
John Wells
John Wells - avatar
+ 2
names = [ "name 1", "name 2", "name 3", "name 4","name 5", "name 6" ] ages= ["12", "18", "22", "5"] for i, n in enumerate(names): try : ages[i] except IndexError: print (n +" doesn't have any age listed") else : print("Name : {} - Age : {} years old".format(n, ages[i]))
23rd Jul 2018, 6:54 PM
DDD
DDD - avatar
+ 1
Thank you, the problem is age [i], right ? for exemple, if names list have 3 elements and ages list have 2 elements, we will have ages[2] in the end >>> index error : list indew out of range
21st Jul 2018, 4:37 AM
DDD
DDD - avatar
+ 1
age
24th Jul 2018, 4:54 PM
David