Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: For In loops - i have no understanding

the resource i am using to learn python has you perform modules within its own website. i think it was originally designed for students of this particular university so that is why i have tagged this with homework, even though it is not.

anyway:

they had me perform this task:

Define a function prod(L) which returns the product of the elements in a list L.

i got this function to work using this code:

def prod(L):
   i = 0
   answer = 1
   x = len(L)
   while i < x:
    answer = answer * L[i]
    i = i + 1
    if i == x:
         return answer

the very next module talks very briefly about For-In loops. and they pose the question:

Define the function prod(L) as before, but this time using the new kind of loop.

i have tried looking through other resources to understand how exactly to use this but i am not following anything. can anybody explain, preferably in plain english, how a for-in loop works?

for reference: here is EVERYTHING that they talked about regarding the for-in loop

Looping through lists It is very common (like in the previous exercise) to loop through every value in a list. Python allows a shortcut to perform this type of an operation, usually called a "for all" loop or a "for each" loop. Specifically, when L is a list, this code

for x in L: «loop body block»

does the following: first x is set to the first value in L and the body is executed; then x is set to the second value in L and the body is executed; this is continued for all items in L.

i just cant fully wrap my head around this. im not looking for answers as i am doing this for knowledge growth - but i feel like im falling behind on this ):

like image 676
kamelkid2 Avatar asked Mar 05 '26 06:03

kamelkid2


1 Answers

Hopefully this simple example will help to clarify, the following two pieces of code do the same thing:

Using a while loop:

L = ['a', 'b', 'c']
i = 0
while i < len(L):
    print L[i]
    i += 1

Using a for loop:

L = ['a', 'b', 'c']
for c in L:
    print c

If you want the index AND the element like you have with a while loop, the pythonic way to do it is with enumerate:

L = ['a', 'b', 'c']
for index, element in enumerate(L): # returns (0,'a'),(1,'b'),(2,'c')
    print index
    print element

As you can see above, the for loop lets you iterate directly over the contents of an iterable, as opposed to the while loop method where you keep track of an index and access items with the index.

like image 179
Andrew Clark Avatar answered Mar 06 '26 19:03

Andrew Clark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!