Python: How to For Loop a list and append to new list

46,793

Solution 1

You return command is inside the loop so as soon as it goes through the first case it returns the value exiting the function.

Here is an example of what your code should look like

a = [100, 1, 10, 2, 3, 5, 8, 13, 21, 34, 55, 98]


def new_list(x):
    new = []
    for item in range(len(x)):            

        if x[item] < 5 and x[item] > 0:
            new.append(x[item])
    return new


print new_list(a)

You can achieve the same result by using a list comprehension

def new_list(x):
    return [item for item in x if 0 < item < 5]

Solution 2

You're resetting new to a brand new empty list each time through the loop, which discards any work done in prior iterations.

Also, in the if statement you're calling return, which exits your function immediately, so you never process the remainder of the list.

You probably wanted something like this instead:

def new_list(x):
    new = []
    for item in x:
        if 0 < item < 5:
            new.append(item)
    return new

Solution 3

Just my recommendation. You could use filter() here instead of a making your own loop.

a = [100, 1, 10, 2, 3, 5, 8, 13, 21, 34, 55, 98]

def new_list(x, low=0, high=5):
    return filter(lambda f: f in range(low, high), x)

Filter returns a new list with elements passing a given predicate and it's equivalent to

[item for item in iterable if function(item)]

as per the documentation.

Therefore

print new_list(a)

Results in:

[1, 2, 3, 5]

This way you can check any values such as:

print new_list(a, 5, 10)
[5, 8]
Share:
46,793
sltdev
Author by

sltdev

Updated on November 10, 2020

Comments

  • sltdev
    sltdev over 3 years

    Practicing my python.

    Task: Loop through list A and create a new list with only items form list A that's between 0-5.

    What am I doing wrong here

    a = [100, 1, 10, 2, 3, 5, 8, 13, 21, 34, 55, 98]
    
    
    def new_list(x):
    
        for item in range(len(x)):
            new = []
    
            if x[item] < 5 and x[item] > 0:
                (new.append(item))
                return new
    
    
    print(new_list(a))
    

    I'm just getting [1] as an answer.

  • timgeb
    timgeb over 5 years
    You are appending the index, not the list element. item is the index in this code. This code outputs [1, 3, 4] but 4 is not even in the list.
  • Daniel
    Daniel over 5 years
    @timgeb you are right. edited to reflect the correction