-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
  • 90,369
  • 161
  • 124
  • 175
Denis
  • 37
  • 6

2 Answers2

3

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,161
  • 1
  • 6
  • 19
rangeseeker
  • 379
  • 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
  • 56
  • 1
  • 5