Home > Mobile >  Slice list in loop by step
Slice list in loop by step

Time:11-01

looking for a nice way to solve slice problem.

list_a = [1,2,3,4,5,6,7,8,9,10,11]
step = 5
print -> [1,2,3,4,5]
print -> [6,7,8,9,10]
print -> [11]

CodePudding user response:

This is what you want to do:

output = [list_a[i:i   step] for i in range(0, len(list_a), step)]

When you pass:

list_a = ['1','2','3','4','5','6','7','8','9','10']

You will get like this:

output = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'], ['10']]

CodePudding user response:

Just use slice notation: list_a[:step]. With try and except: try: print(list_a[:step]) except: print('Out of Range')

  • Related