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’]] `