Change language

Python | Splitting a list of strings by lines

| |

Method: Using loop + index () + slicing list
This task can be accomplished using the above functions together. In this, we’ll just loop over the pairs and get the desired indexes using index () . Then the list is sliced ​​to create a new list of the desired slice and add it to form a new resulting list.

# Python3 code to demonstrate how it works
# Splitting the line list by lines
# using loop + index () + slicing list

 
# initialize the list

test_list = [ ’gfg’ , ’ is’ , ’best’ , "for" , ’CS’ , ’and’ , ’ Maths’ ]

 
# initialize split list

split_list = [( ’ gfg’ , ’best’ ), ( ’CS’ , ’ Maths’ )]

 
# print original list

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

 
# print a split list

print ( "The split list is:" + str (split_list))

 
# Splitting the list of lines by lines
# using a loop + index () + slicing list

for start, end in split_list:

  temp1 = test_list.index (start)

temp2 = test_list.index (end) + 1

test_list [temp1: temp2] = [test_list [temp1: temp2]]

 
# print result

print ( " The resultant split list is: " + str ( test_list))

Output:

 The original list is: [’gfg’,’ is’, ’best’,’ for’, ’CS’,’ and’, ’Maths’] The split list is: [(’ gfg’, ’best’), (’CS’,’ Maths’)] The resultant split list is: [[’gfg’,’ is’, ’best’],’ for’, [’CS’,’ and’, ’Maths’]] 

Python | Splitting a list of strings by lines Python functions: Questions

Python | Splitting a list of strings by lines split: Questions

Shop

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

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

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