mixi
mixi

Reputation: 65

Python list slicing and indexing, better way

I have a given number 15. I have to group it with each group of 5 elements, and get tuple as follows.

num = 15
div = int(15/3)


groups = list(zip(range(div), range(div, div+div), range(div+div, div+div+div)))

for group in groups:
   print (group)


(0, 5, 10)
(1, 6, 11)
(2, 7, 12)
(3, 8, 13)
(4, 9, 14)

It is printing expected result. However, what would be better way of doing it?

Upvotes: 0

Views: 63

Answers (2)

Oliver.R
Oliver.R

Reputation: 1368

To specifically use slicing, you step by div in a slice of list(range(num)):

num = 15
div = int(15/3)
num_list = list(range(num))

for idx in range(div):
    print(num_list[idx::div])

Edit: including num_list optimisation thanks to @Jordan Brière.

Upvotes: 3

Kenan
Kenan

Reputation: 14094

You can do this pretty easy in one line, maybe I'm missing something

lst = [(i, i+div, i+2*div) for i in range(div)]

[(0, 5, 10), (1, 6, 11), (2, 7, 12), (3, 8, 13), (4, 9, 14)]

Upvotes: 1

Related Questions