As @Dereje1 pointed out, the biggest difference (other than what I think is a typo) is what x
is equal to in each iteration of the for
loop. Since this particular loop doesn’t need to reference x
, there isn’t a functional difference in the end. Your loop only needs to do something six times, both loop setups accomplish this. But in a lot of loop instances the item or the item’s index in the list needs to be known.
Consider these:
example = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
# If you only need to access each item of example individually:
for x in example:
print(x)
# a
# b
# c
# d
# e
# f
# g
# But what if we need to access or compare other items of the list in each loop iteration?
# Knowing the list index at each iteration makes this possible
for i in range(len(example)): # len(example) == 7 --> range(7) --> [0, 1, 2, 3, 4, 5, 6]
if i > 0:
print(f"Item i: {example[i]}, Item i-1: {example[i-1]}, Current Index: {i}")
# Item i: b, Item i-1: a, Current Index: 1
# Item i: c, Item i-1: b, Current Index: 2
# Item i: d, Item i-1: c, Current Index: 3
# Item i: e, Item i-1: d, Current Index: 4
# Item i: f, Item i-1: e, Current Index: 5
# Item i: g, Item i-1: f, Current Index: 6
#Python also offers the enumerate() function for such cases
for i, x in enumerate(example):
print(f"Index: {i}, Item: {x}")
# Index: 0, Item: a
# Index: 1, Item: b
# Index: 2, Item: c
# Index: 3, Item: d
# Index: 4, Item: e
# Index: 5, Item: f
# Index: 6, Item: g
# All of these can be used as list comprehensions as well.
test = [(f"i: {i}", f"x: {x}") for i,x in enumerate(example)]
print(f"Array of results: {test}")
# Array of results: [('i: 0', 'x: a'), ('i: 1', 'x: b'), ('i: 2', 'x: c'), ('i: 3', 'x: d'), ('i: 4', 'x: e'), ('i: 5', 'x: f'), ('i: 6', 'x: g')]