kxrosene
kxrosene

Reputation: 67

Is there a way to use loop iteration variables in an area outside the loop?

I want this code to refer to a list with a loop variable inside instead of using the initialised value:

i = 1
list = [i,i+1,i+2]
for i in range(3):
  print(list[0])

I expected the output to be:

0
1
2

The output was:

1
1
1

I have tried i = None instead, but an error was (of course) raised.

I have tried using a placeholder inside the loop to refer to:

x = 1
list = [x,x+1,x+2]
for i in range(3):
  x = i
  print(list[0])

I'm new to Python so I'm not very knowledgeable, hence why I asked. How can I solve this?

Upvotes: 0

Views: 52

Answers (2)

kxrosene
kxrosene

Reputation: 67

The solution turned out to be as simple as redefining the list within the loop.

i = 1
lst = [i,i+1,i+2]
for i in range(3):
  lst = [i,i+1,i+2]
  print(list[0])

It wasn't quite what I hoped for, but I'll make do. Thanks for your help!

Upvotes: 0

Wolric
Wolric

Reputation: 767

In each iteration of your loop you access the same element at index 0. To get to each individual element of your list by index you have set it to i:

x = 1
lst = [x,x+1,x+2]
for i in range(3):
  print(lst[i])

I changed list to lst as the former is a reserved keyword and shouldn't be used as variable name.

Upvotes: 1

Related Questions