2020-06-23
|~2 min read
|225 words
Previously, I wrote about basic use cases of list comprehension in Python.
Today’s example is slightly different and has to do with chunking an input into approximately even parts.1
So, for example, given the string ABCDEFGH
, if I want strings that are 3 characters long, how can I do that?
def split_string(string, size):
return [string[i:i+size] for i in range(0, len(string), size)]
Let’s break this down (for a summary of the different parts of the syntax, refer to my previous post on list comprehension basics):
string[i:i+size]
- which is a slice of the input from i
to i+size
(where size is the length of the chunk)i in range(0, len(string), size)
, i.e. we’re making a new list in the list comprehension to loop over. In this case, we’re starting at position 0, and iterating until the end of the list.Another way to see this would be to take it step-by-step:
def split_simple(string, size):
result = []
for i in range(0, len(string), size):
result.append(string[i:i+size])
return result
Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!