Prev: list.pop(0) vs. collections.dequeue
Next: how can i know if a python object have a attribute such as 'attr1'?
From: Stefan Behnel on 23 Jan 2010 12:34 ceciliaseidel(a)gmx.de, 23.01.2010 17:29: > Arnaud Delobelle wrote: >> ceciliaseidel(a)gmx.de writes: >> >>> As you were talking about list.pop()... >>> >>> Is anyone able to reproduce the following and explain why this happens >>> by chance? (Using 3.1.1) >>> >>> l1 = ["ready", "steady", "go"] >>> l2 = ["one", "two", "tree"] >>> l3 = ["lift off"] >>> >>> for w in l1: > > Ouch... thanks Arnaud... The stable way would've been > > for w in l1[:]: #use copy of l1 for iteration > print(l1.pop()) #decomposite list If the intention is to exhaust the list during the iteration, I'd go for this: while l1: print(l1.pop()) Stefan
From: Steven D'Aprano on 23 Jan 2010 12:44 On Sat, 23 Jan 2010 18:29:33 +0100, Roel Schroeven wrote: >> for w in l1[:]: #use copy of l1 for iteration >> print(l1.pop()) #decomposite list > > I would prefer: > > while l1: > print(l1.pop()) I would prefer: for x in reversed(l1): print(x) l1[:] = [] And garbage dispose of the entire list in one go, instead of an item at a time. -- Steven
From: Stefan Behnel on 24 Jan 2010 07:02 Steven D'Aprano, 23.01.2010 18:44: > On Sat, 23 Jan 2010 18:29:33 +0100, Roel Schroeven wrote: > >>> for w in l1[:]: #use copy of l1 for iteration >>> print(l1.pop()) #decomposite list >> I would prefer: >> >> while l1: >> print(l1.pop()) > > > I would prefer: > > for x in reversed(l1): > print(x) > l1[:] = [] > > > And garbage dispose of the entire list in one go, instead of an item at a > time. IIRC, that's what CPython does anyway, so no need to make this more complex than necessary. Stefan
First
|
Prev
|
Pages: 1 2 Prev: list.pop(0) vs. collections.dequeue Next: how can i know if a python object have a attribute such as 'attr1'? |