Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to solve this 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.

like image 925
sltdev Avatar asked Dec 11 '22 04:12

sltdev


2 Answers

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]
like image 174
Daniel Avatar answered Dec 12 '22 18:12

Daniel


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
like image 30
John Gordon Avatar answered Dec 12 '22 18:12

John Gordon