Reputation: 55
I want my program to loop through a given list and return all integars that are below 5.
for some reason it does this but stops as soon as it hits five instead of continuing through the list.
import os
os.system('cls' if os.name == 'nt' else 'clear')
def ace(a):
d = []
h = len(a)
for i in a:
if i < 5:
d.append(i)
continue
else:
continue
return d
m = [1, 2, 4, 3, 3, 5]
print ace(m)
Upvotes: 0
Views: 81
Reputation: 26
Your code would work fine, however, your return statement is wrongly placed inside the for loop. For it to work you would have to remove one indent, placing it outside the for loop but still inside the function. However, there are better and cleaner pythonic ways of doing it. You can use a filter function with a anonymous lambda function:
def ace(a):
return list(filter(lambda x: x < 5, a))
m = [1, 2, 4, 3, 3, 5]
print (ace(m))
Or you can use a list comprehension instead of a filter function:
def ace(a):
return [number for number in a if number < 5]
m = [1, 2, 4, 3, 3, 5]
print (ace(m))
Upvotes: 1
Reputation: 77847
First, to fix your code, the main problem is that the return is inside the loop. You should return only after the loop is done. Also, you have useless code in the loop: a continue as the last statement does nothing, and you never use the value of h. Shorten it to this:
def ace(a):
d = []
for i in a:
if i < 5:
d.append(i)
return d
That cleans it up your way. As others have already noted, Python has a structure called a comprehension that allows you to build lists, tuples, dictionaries, and generators from iteration constructs.
return [_ for _ in a if _ < 5]
Will do the function in a single line.
Upvotes: 0
Reputation: 12920
you can use the list comprehension for this, which would be easy. You can return this list.
Read more about list comprehension here https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions`
m = [1, 2, 4, 3, 3, 5]
new_list = [value for value in m if value < 5]`
After this new_list will contain [1, 2, 4, 3, 3]
Upvotes: 0
Reputation: 4050
The return statement should be outside the loop.
The function can be also be written as:
def ace(a):
return [ i for i in a if i<5 ]
Upvotes: 0