Reputation: 1
I am practicing coding and I would like some help. Here is the prompt: 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 that are less than 5.
Extras:
Here is my code:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
number = int(input("Pick a number: "))
new_list = []
for item in a:
if item < number:
new_list.append(item)
print(new_list)
The problem I keep running into is whenever I run it and use any number (In this case, I chose 5), I keep getting this result:
Pick a number: 5
[1]
[1, 1]
[1, 1, 2]
[1, 1, 2, 3]
[1, 1, 2, 3]
[1, 1, 2, 3]
[1, 1, 2, 3]
[1, 1, 2, 3]
[1, 1, 2, 3]
[1, 1, 2, 3]
[1, 1, 2, 3]
Can someone please help me?
Upvotes: 0
Views: 665
Reputation: 346
Although Daniel has already given the answer IMHO, but I'd like to add a little more, in case the 2nd requirement is still alive after the 3rd one.
target = int(input("Pick a number: "));print([x for x in a if x < target])
;
here is used to put some simple statements on one line.
For details, please refer How to put multiple statements in one line?
Upvotes: 0
Reputation: 4980
Besides the earlier post to point out the mis-placed of print
statement, you could achieve the same result as this one-liner:
# one-liner
result = [x for x in a if x < number]
print(result)
Upvotes: 1
Reputation: 525
You need to move your print(new_list) statement outside of the for loop.
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
number = int(input("Pick a number: "))
new_list = []
for item in a:
if item < number:
new_list.append(item)
print(new_list)
Upvotes: 0