-1
list = ['a', 'b', 'c', 'd']

#first option
k=0
for thing in list:
  print(thing)
  k=k+1

#second option
for thing in list:
  print(thing)

The two options below output the same result. Is there a reason to prefer one over the other?

Also, what happens when the value of k becomes 4 in the first option? Is it just somehow hard-coded in Python that when all the elements of a list of length n have been "used up", then the algorithm is forced to stop at step n (i.e., when the counter becomes k=n)?

user125234
  • 113
  • 4
  • 4
    they are both the same, the thing you are doing `k=k+1` is doing nothing in logic. – shivankgtm Feb 15 '23 at 20:28
  • 1
    If you want to know the count, you can use `enumerate` rather than making your own variable and incrementing it: https://stackoverflow.com/questions/522563/accessing-the-index-in-for-loops?rq=1 – slothrop Feb 15 '23 at 20:29
  • 2
    Firstly the second option is preferred. However, if you want to have `k` available while you are looping, then you would use: `for k,thing in enumerate(list):` – quamrana Feb 15 '23 at 20:29
  • 1
    And as a side note - don't use `list` as name – buran Feb 15 '23 at 20:31
  • Why would anyone prefer extra code that's of no use? I don't see why you're asking that. – Kelly Bundy Feb 15 '23 at 21:16

1 Answers1

2

for iterates over a list using an internal counter. (Actually the for loop calls the list's __iter__() method and it's the listiterator returned by that method that maintains the counter, but that's a detail.) It starts the counter at 0 and increments it on each pass through the loop, until it reaches the end.

If you need the index for your own purposes, you can maintain it yourself as in your first option, or, better, you can use enumerate():

for k, thing in enumerate(list):
    # etc

You could also use range to iterate over the indexes and get the list item from that. In general this isn't the best way to do it, but I'm showing it for completeness.

for k in range(len(list)):
    thing = list[k]
    # etc
kindall
  • 178,883
  • 35
  • 278
  • 309