Reputation: 158
Say I have a list, l
, which contains [5, 10, 15, 16, 20]
. I want to get the first elements that are all divisible by 5
(so the first three elements), without the last 20
. How do I do this? I've done:
done = False
i = 0
while not done and i < len(l):
if l[i] % 5 == 0:
answer.append(source[i])
else:
done = True
i += 1
However, this seems inefficient. Is there any better way to do this?
Upvotes: 3
Views: 1228
Reputation: 1
you can use something like this
mylist = [5, 10, 15, 16, 20]
result = []
for item in mylist:
if item % 5 != 0:
break
result.append(item)
print(result)
Upvotes: 0
Reputation: 5560
Your idea is actually an efficient answer because it avoids processing more elements than needed. @SamEstep's answer should be the accepted answer because it uses itertools
exactly as intended, but regardless, the correct setup for your code would be the following:
l = [5, 10, 15, 16, 20]
result = []
for elem in l:
if elem % 5 == 0:
result.append(elem)
else:
break
# [5, 10, 15]
As a side note: a while
loop that just indexes a list is discouraged, because it makes your intentions less explicit, and it makes your code more prone to bugs, as you have to handle the indexing yourself. A better way to write it would be to write:
for i in range(len(l)):
which gives you an index for each element in the list. However, if all you're going to do is index the list, then you can just iterate through each item in the list, which adds readability (this is what I've done above):
for elem in l:
If you need both the index and the element, use enumerate
:
for idx, elem in enumerate(l):
This will make your code more readable, and less bug-prone.
Upvotes: 3
Reputation: 305
It's not really inefficient, but probably a clearer way would be -
l = [5, 10, 15, 16, 20]
result = []
for item in l:
if item % 5 == 0:
result.append(item)
else:
break
this gives [5, 10, 15]
Upvotes: 0
Reputation: 91
Say you have myList and you want to find items in it that can be divided by n:
myList = [1,2,10,12,5,20]
ansList = []
ansCount = 0
for i in myList:
if i % n == 0:
# condition is true, do whaterver you want with "i"; here I added it to a new list(ansList)
ansList.append(i)
ansCount += 1
# you can also break the loop as your wish
if ansCount > 2:
break
Upvotes: 0
Reputation: 13294
The itertools.takewhile
function seems like what you want:
from itertools import takewhile
list(takewhile(lambda x: x % 5 == 0, [5, 10, 15, 16, 20]))
This returns [5, 10, 15]
.
Upvotes: 7