Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Split a list into sub-lists based on index ranges

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] 
like image 248
2one Avatar asked Sep 02 '13 10:09

2one


People also ask

How do you split a list into a sublist in Python?

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.

How do you split a specific index in Python?

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.

How do you split a list into evenly sized chunks?

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.


1 Answers

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.

like image 185
TerryA Avatar answered Sep 27 '22 20:09

TerryA