Remove the first element and add it to last in Python List

There are many ways of doing it, here are a few ways-
1. pop method – list.pop()
2. slicing – list[:1],list[1:]

Here is an example for you-

# code
# www.codewindow.in

a=[100,111,122,132,144]
d=["code","window","repeat"]

#using pop method
x=a.pop(0)
a.append(x)
print(a)

#using slicing
y,d=d[:1],d[1:]
d.extend(y)
print(d)

Output:

[111, 122, 132, 144, 100]
['window', 'repeat', 'code']

Explanation:
Here,
pop(0) pops the first element from the list. Then the popped element is added to the last using append() method.
d[:1] slices the array/list till index 0 which means the element at index 0 is assigned to variable ‘y‘ and d[1:] slice the list/array from index 1 leaving the first element (index 0) which is updated on the list ‘d‘. Then the element in ‘y’ is extended to the list ‘d’ i.e. the first element is added to the last.


Also checkout

Leave a Comment

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