Home > Software design >  How can I change the order of items in a python list? [closed]
How can I change the order of items in a python list? [closed]

Time:09-17

for example a list such as:

fruits = ["apple", "pears", "apples", "pineapple"]

how can I reorder such a list such that the third item becomes the first item and the first item becomes the second item?

CodePudding user response:

Try this:-

fruits = ["apple", "pears", "apples", "pineapple"]
order = [1, 0, 2, 3]
my_list = [my_list[i] for i in order]
print(my_list)

Result:-

['pears', 'apple', 'apples', 'pineapple']

CodePudding user response:

It seems you want to rotate the first three elements of your list.

One way to do that is:

fruits[:3] = fruits[2], *fruits[:2]
  • Related