Dasher
Dasher

Reputation: 13

what's the difference between two kinds of iteration of list

Here is my code i got two different output which are [2] and [2,4,6], can someone do some explanation?

list = [1,2,3]
def getdouble(l):
    result = []
    for i in l :
        i = i * 2
        result.append(i)
    return result

print getdouble(list)

def getdouble_v2 (l):
    result = []
    for i in range(len(l)):
        l[i] = l[i] * 2
        result.append(l[i])
    return result

print getdouble_v2(list)

Upvotes: 0

Views: 91

Answers (3)

John La Rooy
John La Rooy

Reputation: 304175

You are using 4 spaces for indentation except for the line

        return result

which is indented by a tab. This is unfortunate because your editor shows the tab as 4 spaces, but Python treats it as 8 spaces, so the code looks like this to Python

list = [1,2,3]
def getdouble(l):
    result = []
    for i in l :
        i = i * 2
        result.append(i)
        return result

So you see, it's returning after the first item is appended to the list

Upvotes: 0

pemistahl
pemistahl

Reputation: 9584

Both functions return the same result list for the same input list. However the second function modifies the original list as well in the line l[i] = l[i] * 2. The first function does not.

So, the results for the first function are:

l = [1,2,3]
result = [2,4,6]

The results for the second function are:

l = [2,4,6]
result = [2,4,6]

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

The only way to get the output you claim is if the indentation in your file is broken. Verify that you're not mixing spaces and tabs with python -tt.

Upvotes: 2

Related Questions