0

I have got a list called words_list that has around 28352 elements (words). Now I want to split this list into 29 different lists each having 1000 elements i.e, the first list would contain first 1000 words and the next list would contain next 1000 words from the words_list and so on. I implemented this in the following manner,

split=[]
start=0
end=1000
for i in range(0,29):
    temp=words_list[start:end]
    split.append(temp)
    start=start+1000
    end=end+1000

The code is serving the purpose. I just want to know, is there any way to reduce the steps?

Souvik Das
  • 29
  • 5
  • search "chunking" on here, probably with python keyword, too. sec ... yeah that one. – Kenny Ostrom May 17 '20 at 15:39
  • 5
    Does this answer your question? [How do you split a list into evenly sized chunks?](https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks) – fixatd May 17 '20 at 15:39
  • 3
    This one-liner might work `chunks = [words_list[x:x+1000] for x in range(0, len(words_list), 1000)]` as mentioned here https://stackoverflow.com/questions/9671224/split-a-python-list-into-other-sublists-i-e-smaller-lists – sagar1025 May 17 '20 at 15:45

1 Answers1

1

Try something like this

split = []
tmp = []
for (count, value) in enumerate(words_list, start=1):
    tmp.append(value)

    # Check if we're on a multiple of 1000
    if count % 1000 == 0:
        split.append(tmp)
        tmp = []

# Add any leftovers
if len(tmp) != 0:
    split.append(tmp)
txk2048
  • 281
  • 3
  • 15
  • Manipulating the items one by one is very inefficient, it's much faster to use slices. See the duplicate for some interesting and efficient ideas! – Thierry Lathuille May 17 '20 at 15:54
  • My main focus was to make the snippet easy to understand, to quote the Zen of Python "Simple is better than complex" and "Readability counts" – txk2048 May 17 '20 at 15:57