0

I was wondering which was the better option for looping through arrays between these two implementations. The first one uses an extra variable ('count'), but has a neater 'for' line, whereas the second one saves on a variable but has to use the 'range' and 'len' function Is there a better option? Or is it up to personal preference? Thanks

# First implementation
names = ["Phil", "Quentin", "Rachel", "Simone"]
scores = [45, 27, 83, 63]
count = 0

for person in names:
    line = person + " scored " + str(scores[count])
    print(line)
    count += 1

# Second implementation
names = ["Phil", "Quentin", "Rachel", "Simone"]
scores = [45, 27, 83, 63]

for i in range(0, len(names)):
    line = names[i] + " scored " + str(scores[i])
    print(line)
  • Or one can use `enumerate()` for a more way to iterate over both the key and its associated index; or one can use `zip()` to iterate over both lists in parallel; there are a great many choices, and [we generally don't allow questions about picking a "best practice" here](https://meta.stackexchange.com/questions/142353/why-is-asking-a-question-on-best-practice-a-bad-thing). – Charles Duffy May 31 '21 at 16:48
  • (`for person, i in enumerate(names): print("f{person} scored {scores[i]}")`) – Charles Duffy May 31 '21 at 16:49

1 Answers1

0

Try the pythonic way by zipping two lists:

for name, score in zip(names, scores):
    print(f"{name} scored {score}")
Tinu
  • 2,432
  • 2
  • 8
  • 20