+ 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]))
5 Antworten
+ 4
yes
+ 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.
+ 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]))
+ 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
+ 1
age