How to change the position of an element in a list in Python

In this article, we’ll take a gander at a few potential ways to deal with fixing the Shift components of a list utilizing Python.

Shift Elements in Python List

Method 1

To move an element at some specific locationĀ in a list:

Step 1: To delete an element from a list, use the list.remove() function.
Step 2: To put a value into a list at a precise location, use the list.insert() function.

Python Code:

list = ['aman','satyam','ammy','sayam']
print(list)
delete_item = 'sayam'
list.remove(delete_item)
list.insert(0, delete_item)
print(list) 

The output will be:

['aman', 'satyam', 'ammy', 'sayam']
['sayam', 'aman', 'satyam', 'ammy']

 

Description:

  • First, we create a list and print that list
  • After that, the first item in the list with a value that matches the parameter supplied is removed using the list.remove() function. If there isn’t an item, the method produces a Value-error.
  • The original list is altered using the delete() function, which also returns None.
  • To enter the data at a specific index, use the insert() function.

In this way, we will move an element at some specific locationĀ in a list

Method 2: using the list.pop()

To move an element’s position in a list:
Step 1: Get the thing’s file in the list by utilizing the list.index() capability.
Step 2: If you need to erase a thing from a list given its record, utilize the list.pop() capability.
Step 3: To add a value to a list at a given index, use the list.insert() function.

Python Code:

list = ['aman', 'satyam', 'ammy', 'sayam']
i= 'sayam'
print(list)

list.insert( 1,list.pop(list.index(i) ))

print(list) 

The output will be:

['aman', 'satyam', 'ammy', 'sayam']
['aman', 'sayam', 'satyam', 'ammy']
>

Description:

  • Here, the first item in the list whose value matches the supplied parameter is returned by the list.index() function.
  • The list.pop() function returns the item that was removed from the list at the specified point.
  • The pop() capability eliminates and returns the last thing in the rundown if no file is given.
  • The value is then inserted into the list at a precise place using the list.insert() function as the last step.

So these are the ways through which we can change the position of an element in a List in Python. I hope you like this article.

Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *