Skip to content

Instantly share code, notes, and snippets.

@InquisitiveDev2016
Created February 19, 2017 19:07
Show Gist options
  • Select an option

  • Save InquisitiveDev2016/87305372cf20a768cfc8ec8450bbb6d8 to your computer and use it in GitHub Desktop.

Select an option

Save InquisitiveDev2016/87305372cf20a768cfc8ec8450bbb6d8 to your computer and use it in GitHub Desktop.
Given a sample list print out all elements less than 5.
""" 1.) Understand the problem
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 that are less than 5.
2.) Plan a solution
Algorithm:
- Create new empty list
- For loop to iterate over each element
- If element < 5:
- Append the element into new list
- Print the new list
3.) Carry out the plan
"""
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
new_list = []
for item in a:
if item < 5:
new_list.append(item)
print(new_list)
""" 4.) Examine your results for accuracy:
b = [1,1,2,3]
"""
@HariSunkiReddy9
Copy link

I've done the same but I've got multiple lists. Why is that?
[1]
[1, 1]
[1, 1, 2]
[1, 1, 2, 3]
[1, 1, 2, 3, 5]

make sure that print should be outside the loop..

@educatedscholar
Copy link

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b=[]
for i in a :
if i <= 5 :
b.append(i)
print(b)

this will give you perfect results.........print is out of loop.
[1, 2, 3, 4, 5] is the output.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment