Change language

Python | Replace a sublist with another in the list

| | |

Method # 1: Using a loop (when a sublist is specified)
This method is used when we know the sublist to be replaced. We accomplish this task using loops and list slicing, and separate the logic for finding the indices that need to be manipulated first and then replaced.

# Python3 demo code work
# Replace the sublist with another in the list
# Using a loop (when a sublist is set)

 
# helper function for finding items

def find_sub_idx (test_list, repl_list, start = 0 ):

  length = len (repl_list) < / code>

for idx in range (start, len (test_list)):

if test_list [idx: idx + length] = = repl_list:

return idx, idx + length

 
# helper function for the final task

def replace_sub (test_list, repl_li st, new_list):

length = len (new_list)

idx = 0

for start, end in iter ( lambda : find_sub_idx (test_list, repl_list, idx), None ):

test_list [start: end] = new_list

idx = start + length

 
# initializing list

test_list = [ 4 , 5 , 6 , 7 , 10 , 2 ]

 
# print original list

print ( "The original list is:" + str (test_list))

  
# Replace list

repl_list = [ 5 , 6 , 7 ]

new_list = [ 11 , 1 ]

 
# Replace the sublist with another in the list
# Using a loop (when a sublist is specified)
replace_sub (test_list, repl_list, new_list)

 
# print result

print ( "List after replacing sublist:" + str (test_list))

Output:

 The original list is: [4, 5, 6, 7, 10, 2] List after replacing sublist: [4, 11, 1, 10 , 2] 

Method # 2: Using list slicing (when the sublist index is given)
This task becomes easier when we just need to replace the base sublist available start and end index, in which case slicing of the list is sufficient to achieve a solution to this problem.

# Python3 code to demonstrate how it works
# Replace the sublist with another in the list
# Use list slicing (when a sublist is specified squeak)

 
# initializing list

test_list = [ 4 , 5 , 6 , 7 , 10 , 2 ]

 
# print original list

print ( " The original list is: " + str (test_list))

  
# Replace sleep juice

repl_list_strt_idx = 1

repl_list_end_idx = 4

new_list = [ 11 , 1 ]

 
# Replace the sublist with another in the list
# Using list slicing (when a sublist index is specified)

test_list [repl_list_strt_idx: repl_list_end_idx] = new_list

 
# print result

print ( "List after replacing sublist:" + str (test_list))

Output:

 The original list is: [4, 5, 6, 7, 10, 2] List after replacing sublist: [4, 11, 1, 10, 2] 

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

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically