SunGone
SunGone

Reputation: 21

How do I print this as a new list?

I want the program to print the numbers within the a list as a new list - the x list, instead of printing each number within its own list.

When I run this, the output is:

[1]
[1, 1]
[1, 1, 2]
[1, 1, 2, 3]

When I only want:

[1, 1, 2, 3]

This is, like, the easiest thing to do and I can't remember how to do it! Can someone help me? Thanks.

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

x = []
def less_than_five():
    for item in a:
        if item < 5:
            x.append(item)
        print(x)

less_than_five()

Upvotes: 1

Views: 76

Answers (4)

CVDE
CVDE

Reputation: 440

Your print statement is in an inner loop. You can fix your code like this:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

x = []
def less_than_five():
    for item in a:
        if item < 5:
            x.append(item)
    print(x)

less_than_five()

Upvotes: 1

Olivier Melan&#231;on
Olivier Melan&#231;on

Reputation: 22324

You could find the index of the first entry which does not meet your condition, and then slice from there. This has the advantage of not traversing your whole list if the condition is met early on.

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

index = 0
while index < len(a) and a[index] < 5:
    index += 1

print(a[:index])
# prints: [1, 1, 2, 3]

Upvotes: 1

niraj
niraj

Reputation: 18218

You need to move print statement out of for loop:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

x = []
def less_than_five():
    for item in a:
        if item < 5:
            x.append(item)
    print(x)

less_than_five()

Result:

[1, 1, 2, 3]

Same result can be achieved with list comprehension:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

x = []

def less_than_five():
    # if original x has to be changed extend is used
    x.extend([item for item in a if item < 5])
    print(x)

less_than_five()

Upvotes: 2

Aaditya Ura
Aaditya Ura

Reputation: 12689

You can filter the result like this:

print(list(filter(lambda x:x<5,a)))

output:

[1, 1, 2, 3]

or you can also try list comprehension :

print([i for i in a if i<5])

output:

[1, 1, 2, 3]

Upvotes: 2

Related Questions