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()

4 answers

  • answered 2018-03-13 21:15 student

    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()
    

  • answered 2018-03-13 21:20 Ayodhyankit Paul

    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]
    

  • answered 2018-03-13 21:29 Olivier Melançon

    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]
    

  • answered 2018-03-13 21:43 Farhad Bat

    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()