Friday 24 September 2021

Python: Reverse the elements of a list

Approach 1: Using reverse method

 

Example

primes.reverse()

 

reverse_list_1.py

primes = [2, 3, 5, 7, 11, 13]
print('primes -> ', primes)

primes.reverse()
print('primes post revers -> ', primes)

 

Output

primes ->  [2, 3, 5, 7, 11, 13]
primes post revers ->  [13, 11, 7, 5, 3, 2]

 

Approach 2: Using Slicing Operator

 

Syntax

list[start_index:end_index:step_size]

 

Example

my_list[2:16:3]

In the above example step size is 3, and the indexes start from 2 and end at 16, so the elements will be incremented by the value of 3 till it reaches the 16th index.

 

Similarly my_list[::-1] is used to reverse the elements of a list.

 

reverse_list_2.py

primes = [2, 3, 5, 7, 11, 13]
primes_reverse = primes[::-1]

print('primes -> ', primes)
print('primes_reverse -> ', primes_reverse)

Output

primes ->  [2, 3, 5, 7, 11, 13]
primes_reverse ->  [13, 11, 7, 5, 3, 2]

Approach 3: Using reversed function

‘reversed’ function return a reverse iterator.

 

reversed_demo_1.py

primes = [2, 3, 5, 7, 11, 13]

for ele in reversed(primes):
    print(ele)

Output

13
11
7
5
3
2

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment