Your end criteria must be formulated a little differently: run the loop while there are items and the bucket is positive. or is not the right operation here.
while unpaid_sales and bucket > 0:
unpaid_sale = unpaid_sales.pop(0)
#do stuff
Answer from tynn on Stack OverflowYour end criteria must be formulated a little differently: run the loop while there are items and the bucket is positive. or is not the right operation here.
while unpaid_sales and bucket > 0:
unpaid_sale = unpaid_sales.pop(0)
#do stuff
Do not use separate whileloops. Do as follows :
while unpaid_sales and bucket > 0 :
unpaid_sale = unpaid_sales.pop(0)
...do stuff
python - Phython - While loop for a list until it is empty - Stack Overflow
Python while loop not ending when list empty - Stack Overflow
Loop until list is not empty in Python - Stack Overflow
While Not Loop for empty list in python - Stack Overflow
images = [ ] for filename in filenames:
Because otherwise without it, if you either refer to it in the loop, it won't exist so you'll get an error. Or if you define it in the loop, you'll redefine it every iteration, destroying all the progress added to it from every previous iteration.
Why do you need to hold an empty cup before pouring water into it?
Based on the other answers, I think the cleanest solutions are
#Handles None return from get_list
for item in get_list() or []:
pass #do something
or the comprehension equiv
result = [item*item for item in get_list() or []]
Use a list comprehension:
def do_something(x):
return x**2
things = []
result = [do_something(x) for x in things]
print result # []
things = [1, 2, 3]
result = [do_something(x) for x in things]
print result # [1, 4, 9]
The problem is the list
lgets smaller after callingl.remove(value), but subscript 'i' still try to index the originall.Based on the above analysis, one solution is to keep
lunchanged in the inner loop, the other is to keep the unseenireduced along withl.
# Create new lists to keep `l` unchanged in the inner loop
def method1():
l = [0, 1, 0, 0, 1, 1]
removed= []
while l:
next_l = []
[next_l.append(v) if v <= 0 else removed.append(i) for i, v in enumerate(l)]
l = [x+1 for x in next_l]
return removed
def method2():
l = [0, 1, 0, 0, 1, 1]
removed= []
while l:
num_del = 0 # record number of deletions in the inner loop
for i in range(len(l)):
if l[i-num_del]>0:
l.remove(l[i-num_del])
num_del += 1
# store the index processing order
removed.append(i)
else:
continue
l = [x+1 for x in l]
return removed
assert method1() == method2()
# output [1, 4, 5, 0, 1, 2]
But I guess you expect the result [1, 4, 5, 0, 2, 3], i.e., record the processing order with subscript in the original list. If so, try this:
l = [0, 1, 0, 0, 1, 1]
el = list(enumerate(l))
removed = []
bound = 0
while len(removed) != len(l):
removed.extend(list(filter(lambda iv: iv[1] > bound, el)))
el = list(filter(lambda iv: iv[1] <= bound, el))
bound -= 1
removed, _ = zip(*removed)
IIUC - it looks like you just want the index of the removed values and keep the values in the original list if they are less than or equal to and then +1 to the value
l = [0, 1, 0, 0, 1, 1]. # your list
keep_idx, lst = zip(*[(idx, i+1) for idx, i in enumerate(l) if i<=0])
print(list(keep_idx)) # -> [0, 2, 3]
print(list(lst)). # -> [1, 1, 1]
Loops and conditionals implicitly use bool on all their conditions. The procedure is documented explicitly in the "Truth Value Testing" section of the docs. For a sequence like a list, this usually ends up being a check of the __len__ method.
bool works like this: first it tries the __bool__ method. If __bool__ is not implemented, it checks if __len__ is nonzero, and if that isn't possible, just returns True.
As with all magic method lookup, Python will only look at the class, never the instance (see Special method lookup). If your question is about how to change the behavior, you will need to subclass. Assigning a single replacement method to an instance dictionary won't work at all.
Great question! It's inspecting bool(a), which (usually) calls type(a).__bool__(a).
Python implements certain things using "magic methods". Basically, if you've got a data type defined like so:
class MyExampleDataType:
def __init__(self, val):
self.val = val
def __bool__(self):
return self.val > 20
Then this code will do what it looks like it'll do:
a = MyExampleDataType(5)
b = MyExampleDataType(30)
if a:
print("Won't print; 5 < 20")
if b:
print("Will print; 30 > 20")
For more information, see the Python Documentation: 3.3 Special Method Names.