cclloyd :
What would be the most pythonic way to move an item to the front of a list, when iterate through the list with a for in
loop?
As such:
for item in items:
if condition:
# Move `item` to front of `items`
break
Sayandip Dutta :
Modifying a list while iterating over it, is generally not recommended, that said:
>>> ctr = 0
>>> lst = [1,2,3,4,5,6]
>>> for i in lst:
...: if ctr == 3:
...: lst.insert(0,lst.pop(ctr))
...: break
...: ctr += 1
...:
>>> lst
[4, 1, 2, 3, 5, 6]
Or,
>>> lst = [1,2,3,4,5,6]
>>> for i,x in enumerate(lst):
... if x == 3:
... lst.insert(0,lst.pop(i))
... break
>>> lst
[3, 1, 2, 4, 5, 6]