-1

I have looked around for information regarding this kind of loop seen here:

listOfStrings = ["hey", "I", "am","still", "here"]
listOfStringsCopy = ["hey", "I", "am", "still", "here"]

for i in range(len(listOfStrings)):
    listOfStrings[i] = "something else"

for word in listOfStringsCopy:
    word = "something else"

print(listOfStrings, listOfStringsCopy)

which returns:

 ['something else', 'something else', 'something else', 'something else', 'something else']
 ['hey', 'I', 'am', 'still', 'here']

I have only begun to catch on now why this particular (for word in) loop seems to be wholly ineffective when you're trying to do anything to the list being looped. I think I recall reading somewhere that for each loops make a copy of the list or something, but have been unable to find anything concrete.

First, am I even referring to this kind of loop correctly? Is the second for loop I ran above a python "for each loop" even though the first loop above has incredibly similar syntax?

Second, can someone explain why this is and if I should stick to the regular first loop when I'm trying to do anything with a list besides key/dictionary processes?

I have read the possible duplicate question and it kind of answers my question in that whenever I need to modify items in a list I need to loop indices, however I still want to know if there is any linguistic delineation between a loop that loops through indices and a loop that loops through elements of a list like in my second loop.

notacorn
  • 3,526
  • 4
  • 30
  • 60
  • It terms of python syntax there isn't a difference between a `for i in range...` and `for x in alist`. Both step through an iterable, a list or range. Also note the use of `enumerate` in some of the duplicate answers. – hpaulj Sep 04 '18 at 04:48
  • If you are replacing each element of a list, it might be faster and simpler to use a list comprehension. – hpaulj Sep 04 '18 at 06:30

1 Answers1

0

Second loop:

for word in listOfStringsCopy:
    word = "something else"

is not modifying the existing list because instead of modifying the list, you are actually re-binding the variable i.e. word, and this is obviously how we would want it to work.

This is equivalent to:

x = [1,2,3,4,5]
y = x[0]
y = "something else"

Now, y does not refer to the first element of the list x, but it now refers to a string "something else".

Ankit Jaiswal
  • 22,859
  • 5
  • 41
  • 64