General question


So in the lecture notes it says below:

Method 1 - for item in list:

for item in list:
print item
Method 2 - iterate through indexes:

for i in range(len(list)):
print list[i]

Method 1 is useful to loop through the list, but it's not possible to modify the list this way. Method 2 uses indexes to loop through the list, making it possible to also modify the list if needed. Since we aren't modifying the list, feel free to use either one on this lesson!

For some reason I think both can be used to modify the list if needed. Can someone explain to me why method 1 doesn't have list modifying abilities? I can just do a for each item in n, n=n+1 or something. Thoughts?

Thanks in advance!


Here ya go,

a = ['Chicken', 'Nuggets']

def modify_list(a_list, to_modify):
    if to_modify in a_list:
        a_list[a_list.index(to_modify)] = "Modified!"
    return a_list

modify_list(a, 'Chicken')

By using the list method of index() we can get the index of a list and just plug that into the list index and change the value that way. Don't even have to loop.


I should also mention if it has more than one of the same item it will grab the first item in the list. Unless you tell it to grab a different one.

a = ['a', 'a', 'a']

print(a.index('a', -1))
print(a.index('a', 1))

See, you can also get the index for all the letters by just looping through and calling the index on that item OR you can do this and just get the index along with the letter.

a = ['a', 'a', 'a']

for index, item in enumerate(a):
    print(index, a)

enumerate gives you access to the index while using loops.