user14234546
user14234546

Reputation:

How to get list output in range

How can we get list output in range ?

suppose n=4 and k =3

so how can we get list [1,2,3,1] where length of array will be n and k is range (1....k)

ex -2

if n=5 and k=3

list will be [1,2,3,1,2]

Upvotes: 1

Views: 111

Answers (6)

Arty
Arty

Reputation: 16747

Short solution:

[i % k + 1 for i in range(n)]

and another a bit longer solution:

[i for j in range((n + k - 1) // k) for i in range(1, k + 1)][:n]

and similar to above but expressed differently

(list(range(1, k + 1)) * ((n + k - 1) // k))[:n]

Upvotes: 1

Seyi Daniel
Seyi Daniel

Reputation: 2379

You can get it done with itertools:

import itertools  
k,n = 3, 5    
result = []    
# defining iterator  
iterators = itertools.cycle(list(range(1,k+1)))  
# for in loop  
for i in range(n):    
    x.append(next(iterators))

print(x)

Upvotes: 0

Michael Szczesny
Michael Szczesny

Reputation: 5026

A solution with itertools.cycle

def rangelist(n, k):
    return [i for i,_ in zip(cycle(range(1,k+1)), range(n))]
rangelist(n=5,k=3)
>>> [1, 2, 3, 1, 2]

Upvotes: 0

Alex Mandelias
Alex Mandelias

Reputation: 517

Try this:

n = 5
k = 3
current_number = 1
ls = []
for count in range(n):
    ls.append(current_number)
    current_number = ((current_number) % k) + 1

Upvotes: 0

Thierry Lathuille
Thierry Lathuille

Reputation: 24282

You can use itertools.cycle to cycle on the values of a range from 1 to k, then use itertools.islice to get n values from it:

from itertools import cycle, islice

k = 3
n = 7

k_cycle = cycle(range(1, k+1))

out = list(islice(k_cycle, n))

print(out)
# [1, 2, 3, 1, 2, 3, 1]

Upvotes: 1

user13897142
user13897142

Reputation:

Try this

n,k = map(int,input().strip().split())
x=[]
for i in range(n):
    x.append(1+i%k)
print(x)

Upvotes: 0

Related Questions