Abdulrahman Abdulla
Abdulrahman Abdulla

Reputation: 11

Adding to a list in a loop

I have recently started learning programming and I'm trying to use what I am learning.

What I am trying to do: I am trying to write a program that will pick positive numbers from a list and add them to an empty list.

The code I wrote:

lst = [5, 4, 3, 1, -2, -3, -5]

lst2 = []

for i in lst:

    if i > 0:

        lst2=lst2.append[i]

    if i <= 0:

        break

print(lst2)

This is my first piece of code, and I would appreciate any form of response. Thank you!

Upvotes: 1

Views: 194

Answers (1)

tzaman
tzaman

Reputation: 47870

That's a good start! A few things:

  1. list.append does not return a modified list, it appends the item to the list directly and returns None. So you don't want to say lst2 = lst2.append(...), just do the append call and that's enough. Also, you need parentheses () and not brackets [] for function calls.
  2. You don't want to call break since it'll quit the whole loop, so if there are any more positive numbers after the first negative is encountered they'll just get skipped. In fact, you don't even need the second if at all, the first one is enough to do what you want.

So:

lst = [5, 4, 3, 1, -2, -3, -5]
lst2 = []

for i in lst:
    if i > 0:
        lst2.append(i)

print(lst2)

The more 'pythonic' way of doing this is by using a list comprehension, which looks like this:

lst =  [5, 4, 3, 1, -2, -3, -5]
lst2 = [i for i in lst if i > 0]

Upvotes: 6

Related Questions