Change language

Python | Flip the list

|

Python provides us with various ways to modify the list. We’ll look at some of the many techniques for modifying a list in Python. 
Examples:

 Input: list = [10, 11, 12, 13, 14, 15] Output: [15, 14, 13, 12, 11, 10] Input: list = [ 4, 5, 6, 7, 8, 9] Output: [9, 8, 7, 6, 5, 4] 

Method 1: using the built-in reversed () function .
In this method, we do not reverse the list in place (modify the original list) and do not create any copy of the list. Instead, we get a reverse iterator, which we use to cycle through the list.

# Reverse the list with reversed ()

def Reverse (lst):

return [ele for ele in reversed (lst)]

 
Driver code

lst = [ 10 , 11 , 12 , 13 , 14 , 15 ]

print (Reverse (lst))

Output:

 [15, 14, 13, 12, 11, 10] 

Method 2. Using the built-in reverse () function .
With the back () method we can completely change the contents of the list object in place i.e. we don’t need to create a new list instead we just copy the existing elements of the original list in reverse order. This method directly modifies the original list.

# Reverse the list using reverse ()

def Reverse (lst):

  lst.reverse ()

  return lst

  

lst = [ 10 , 11 , 12 , 13 , 14 , 15 ]

print (Reverse (lst))

Output:

 [15, 14, 13, 12, 11, 10] 

Method 3: Using the slicing technique.
This method creates a copy of the list and does not sort the list in place. Making a copy requires more storage space for all existing items. This wastes more memory.

# Flip the list using slicing technique

def Reverse (lst):

new_lst = lst [:: - 1 ]

return new_lst

 

lst = [ 10 , 11 , 12 , 13 , 14 , 15 ]

print (Reverse (lst))

Output:

 [15, 14, 13 , 12, 11, 10] 

For a better understanding of the slicing technique, refer to the in Python .

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method