Wolf
Wolf

Reputation: 17

Unexpected result in for / lists (very basic question)

I've been trying to create a very simple list like so:

j = 0
myList = list(range(5))
for i in myList: j = j + 2
print("i=", i, "j=", j)

What I expect is this:

i = 0 , j = 2
i = 1 , j = 4
i = 2 , j = 6 etc

What I get instead is this:

i= 4 j= 10

Where is the mistake?

Upvotes: 0

Views: 67

Answers (3)

AcK
AcK

Reputation: 2178

If you do not need myList (better: my_list) as a list but simply use it to define the range of the for loop you can write it as so:

j = 0
for i in range(5):
    j += 2  # shorter and more pythonic
    print("i=", i, "j=", j)

Upvotes: 1

Shubhangi Chaturvedi
Shubhangi Chaturvedi

Reputation: 157

Problem is with your indentation.

Here,is the corrected code:

j = 0
myList = list(range(5))
for i in myList: 
    j = j + 2
    print("i=", i, "j=", j)

Upvotes: 1

Abhinav Mathur
Abhinav Mathur

Reputation: 8196

The lack of indentation causes the error. It should be

j = 0
myList = list(range(5))
for i in myList: 
    j = j + 2
    print("i=", i, "j=", j)

Upvotes: 5

Related Questions