Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I am having a list that contains 1003 number of elements:

data=["I","am","a","python","programmer".....]

where, len(data)= say 1003

I want to create a subset of this list (data) by dividing the original list into parts of 100. So, as a result:

data_chunk1=[.....] #first 100 items of list data

data_chunk2=[.....] #second 100 items of list data

.

.

.

data_chunk11=[.....] # remainder of the entries,& its len <=100, len(data_chunk_11)=3

Is there a pythonic way to achieve this task? 

1 Answer

0 votes
by (108k points)
edited by

You can execute the below code:

chunks = [data[x:x+100] for x in range(0, len(data), 100)]

If you are working with python 2.x then use the xrange(), changing the above code to:

chunks = [data[x:x+100] for x in xrange(0, len(data), 100)]

 If you are a beginner and want to know more about Python, then do check out the below Python tutorial video that will help you in understanding the topic in a better way:

Browse Categories

...