UPDATED:
In python, how do i split a list into sub-lists based on index ranges
e.g. original list:
list1 = [x,y,z,a,b,c,d,e,f,g]
using index ranges 0 - 4:
list1a = [x,y,z,a,b]
using index ranges 5-9:
list1b = [c,d,e,f,g]
thanks!
I already known the (variable) indices of list elements which contain certain string and want to split the list based on these index values.
Also need to split into variable number of sub-lists! i.e:
list1a list1b . . list1[x]
How do you split a list into two parts in Python? This can be done using the following steps: Get the length of a list using len() function. If the length of the parts is not given, then divide the length of list by 2 using floor operator to get the middle index of the list.
Use the str. split() method to split the string into a list. Access the list element at the specific index. Assign the result to a variable.
The easiest way to split list into equal sized chunks is to use a slice operator successively and shifting initial and final position by a fixed number.
In python, it's called slicing. Here is an example of python's slice notation:
>>> list1 = ['a','b','c','d','e','f','g','h', 'i', 'j', 'k', 'l'] >>> print list1[:5] ['a', 'b', 'c', 'd', 'e'] >>> print list1[-7:] ['f', 'g', 'h', 'i', 'j', 'k', 'l']
Note how you can slice either positively or negatively. When you use a negative number, it means we slice from right to left.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With