-2

Now I have a list like ["apple", "banana", "lemon", "strawberry", "orange"]

If I want to reorder the list, for example:

Insert the strawberry into a new position, then the elements behind the strawberry need to move to the right one step. What should I do?

["apple", "strawberry", "banana", "lemon", "orange"]
Yash Mehta
  • 2,025
  • 3
  • 9
  • 20
kenny
  • 35
  • 6
  • 2
    Does this answer your question? [How to switch position of two items in a Python list?](https://stackoverflow.com/questions/2493920/how-to-switch-position-of-two-items-in-a-python-list) – Robby Cornelissen Jan 27 '23 at 06:35
  • 1
    or if you want to remove one item and insert it into other position, when you can use remove() and insert() functions – Nikolay Jan 27 '23 at 06:37
  • 1
    Does this answer your question? [Move an item inside a list?](https://stackoverflow.com/questions/3173154/move-an-item-inside-a-list) – Pranav Hosangadi Jan 27 '23 at 06:50

1 Answers1

2

You can use insert and pop (in example I also use index for clarity).

x = ["apple", "banana", "lemon", "strawberry", "orange"]
x.insert(1, x.pop(x.index("strawberry")))
print(x)

Prints:

["apple", "strawberry", "banana", "lemon", "orange"]

1 in the insert points to the index in list that you want your value to end up in.

dm2
  • 4,053
  • 3
  • 17
  • 28