Move Item to front of list when using for in loop

Viewed 536

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
5 Answers

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]

It'd be least error-prone to do things the "manual" way:

new_items = []
for item in items:
    if condition:
        new_items.insert(0, item)  # Prepend
    else:
        new_items.append(item)  # Append
# if you need to modify `items` "in-place", assign to a slice:
items[:] = new_items

I would to something like this:

for idx, item in enumerate(items):
   if 'condition on item':
      items.pop(idx)
      items.insert(0, item)

Is it a number we are talking about numbers. In our example, our condition is if number is larger than 2, put it in front of the list else append.

items = [5, 3, -2, 3, 1,]

new_list = []

for item in items:
    if item > 2:
        new_list.insert(0, item)
    else:
        new_list.append(item)

print(new_list)

What this will print out in our new_list.

[3, 3, 5, -2, 1]

Using the slicing technique only:

data = list(range(10))

for i, j in enumerate(data):
    if i == 5:
        # shift all numbers left of j one position to the right
        l[1:i+1] = l[:i]
        l[0] = j
        break

Gives the following result:

>>> data
[5, 0, 1, 2, 3, 4, 6, 7, 8, 9]
Related