0

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)
6
  • 2
    Am I missing something? It looks like the expected and actual output match. Commented Sep 26, 2016 at 23:34
  • @CharlesMcKelvey he needs it formated like [...] not just spaced Commented Sep 26, 2016 at 23:38
  • Are you just asking how to format the output so it looks like [1,1,2,3,5] instead of 1 1 2 3 5? If so, it's probably advisable to drop the part of the question that just recaps the homework problem you were on when this came up. It's confusing as currently presented. Commented Sep 26, 2016 at 23:38
  • It all makes sense now. Thanks all. Commented Sep 26, 2016 at 23:39
  • You state all the elements of the list as the list that are less than 5 but your example [1,1,2,3,5] is less than or equal to 5... Commented Sep 27, 2016 at 3:52

3 Answers 3

1

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]
Sign up to request clarification or add additional context in comments.

2 Comments

Could you also use filter
@cricket_007 Yes, very true. In py2, one could use filter(lambda x: x<=5, a) or, in either py2 or py3, one could use list(filter(lambda x: x<=5, a)).
0

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)

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.