Borislav Hadzhiev
Last updated: Jun 25, 2022
Check out my new book
To split a list every x items:
range()
class to iterate over a range with step X.my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] n = 2 result = [ my_list[idx:idx+n] for idx in range(0, len(my_list), n) ] # 👇️ [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h'], ['i', 'j']] print(result)
We used the range()
class to iterate over a range with a step of N.
my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] n = 2 # 👇️ [0, 2, 4, 6, 8] print(list(range(0, len(my_list), n)))
The range class is
commonly used for looping a specific number of times in for
loops and takes
the following parameters:
Name | Description |
---|---|
start | An integer representing the start of the range (defaults to 0 ) |
stop | Go up to, but not including the provided integer |
step | Range will consist of every N numbers from start to stop (defaults to 1 ) |
The indexes in the range are the indexes of the first list item in each nested list.
On each iteration we get a slice that starts at the current index and ends at the current index + N.
The example above uses a list comprehension to iterate over the range.
You can also use a for
loop to achieve the same result.
my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] n = 2 result = [] for idx in range(0, len(my_list), n): result.append(my_list[idx:idx+n]) # 👇️ [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h'], ['i', 'j']] print(result)
This for
loop is the equivalent of the list comprehension we previously used.