-1

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]
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Denis
  • 69
  • 9

2 Answers2

4

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']]
Python learner
  • 1,159
  • 1
  • 8
  • 20
rangeseeker
  • 395
  • 2
  • 9
1

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

random
  • 62
  • 1
  • 7