/  Technology   /  How can I reverse a list in Python?
How can I reverse a list in Python?

How can I reverse a list in Python?

We can reverse a given list using the following methods.

  • Using reverse()
  • Using slicing
  • Using slice()
  • Using for loop
  • Using reversed()

 

1. Using reverse():

The reverse() method reverses the elements of the list in-place, which means it makes changes to the existing list and doesn’t create any new list. So we can’t store the result in a new variable. That is the reason we are getting None as the output when we are trying to print new_list in the below example.

 

Example:

demo_list = [1,2,3,4]
demo_list.reverse()
print(demo_list)

new_list = demo_list.reverse()
print(new_list)

Output:

 

2. Using slicing:

Before learning to implement slicing for reversing a list, go through the article on slicing. 

 

In the slice notation, by omitting the start and end arguments we can print the entire list and by giving a negative number as the step value, we can print the elements from the right end. Using this approach doesn’t affect the original list, a new list is created and the reversed list is stored in this, reversed_list here. 

 

Example:

demo_list = [1,2,3,4,5,6]

reversed_list = demo_list[::-1]
print('Original list: ',demo_list)
print('reversed list: ',reversed_list)

Output:

 

3. Using slice():

The slice() method accepts the same arguments as the slice notation, start, end, step. Here instead of omitting the start and end arguments, we pass None. This method returns a slice object which internally performs the slicing operation. 

 

Example:

demo_list = [1,2,3,4,5,6]

slice_obj = slice(None, None, -1)
print('slice_obj type: ',type(slice_obj))
print('reversed list: ',demo_list[slice_obj])

Output:

4. Using for loop:

Here we use a combination of append() and pop() methods. We use the pop() method which removes the last element in any given sequence and we add this removed element to a new empty list named reversed_list using the list method append()

 

Example:

demo_list = [1,2,3,4,]
reversed_list = []

for i in range(len(demo_list)):
    reversed_list.append(demo_list.pop())
print(reversed_list)

Output:

 

5. Using reversed():

The reversed() method returns an iterator that iterates the given sequence in the reversed order and adds each element to a new list, reversed_list using the list method append().

 

Example:

demo_list = [1,2,3,4,]
reversed_list = []

for i in reversed(demo_list)):
    reversed_list.append(i)
print(reversed_list)

Output:

 

Leave a comment