For loops question

Can someone explain why or what happens in these different for loop examples? I can’t seem to figure out when to use one or the other.

for power in powers:

for i in range(len

Hello @css6229729037.

Welcome to the forums.

The for...in loop uses a placeholder variable that will be assigned the value of each element of the list in turn.

The for i in range(len(powers)): loop assigns numbers to i starting with 0, and going up to but not including the value of the len(powers). i would commonly be referred to as an index variable in this case because we would typically use it to access the elements of the powers list by their index.

Consider the following examples:

powers = ['flying', 'laser vision', 'x-ray vision', 'strength', 'speed']

print("Powers using for...in:")
for power in powers:
    print(power) #power is a placeholer for each element of the list

print("\nvalue of i using for i in range(len(powers)):")    
for i in range(len(powers)):
    print(i) #i is a number that could be used to access each element of the list by inex

print("\nPowers using for i in range(len(powers)):")
#access the elements of powers by index
for i in range(len(powers)):
    print(powers[i])

Output:

Powers using for…in:
flying
laser vision
x-ray vision
strength
speed

value of i using for i in range(len(powers)):
0
1
2
3
4

Powers using for i in range(len(powers)):
flying
laser vision
x-ray vision
strength
speed

If you don’t need to know the index of each element, for power in powers will give you each element in turn. You can perform whichever actions you need to on each element, or on specific elements with code inside your loop. If you need to know the index, the for i in range() loop may be the way to go. There are other ways that you’ll learn as you continue. It’s up to you, the programmer, to decide which method best suits the task at hand.

1 Like

Thanks, that really helps.

1 Like

This topic was automatically closed 18 hours after the last reply. New replies are no longer allowed.