barbapapa
barbapapa

Reputation: 11

Convert int to list in python

Take a list, say for example this one:

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

and write a program that prints out all the elements of the list as the list [1,1,2,3,5] that are less than 5. Currently it prints as

1
1
2
3
5

My code

a = [1,1,2,3,5,8,13,21,34,55,89]
count = 0
for i in a:
    if i<=5:
        count+=1
        print(i)

Upvotes: 0

Views: 2015

Answers (3)

SorMun
SorMun

Reputation: 105

You should have the if condition be more strict if you want only element smaller than 5. It should be if i<5: instead of i<=5.

If you want to store the elements in a new list, see the example below.

a = [1,1,2,3,5,8,13,21,34,55,89]
new_list=[]
for i in a:
    if i<5:
        new_list.append(i)
print new_list

Upvotes: 0

John1024
John1024

Reputation: 113824

To have it print out as a list, keep it as a list. You can use list comprehension to accomplish this:

>>> a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> [i for i in a if i<=5]
[1, 1, 2, 3, 5]

If we use print, it still looks the same:

>>> print([i for i in a if i<=5])
[1, 1, 2, 3, 5]

Upvotes: 1

Justin Besteman
Justin Besteman

Reputation: 398

If you want all to print out all the element that great and equal to 5 then you are doing it right. But if you want to print out less then 5 you want:

for i in a:
    if i < 5:
        count += 1
        print(i)

Upvotes: 0

Related Questions