0

I have written following code for make list.

# in_put = 3,4
# 3 item in each sublist
# total 4 sublist
# out_put = [ [1,2,3] , [4,5,6] , [7,8,9] , [10,11,12] ]

def my_lc(m,n):
    out_put = []
    temp = []
    element =1
    for i in range(1,n+1):
        for j in range(1,m+1):
            temp.append(element)
            element += 1
        out_put.append(temp.copy())
        temp.clear()
    return out_put

print(my_lc(3,4))

How can write my_lc() function using list comprehension?

0

1 Answer 1

1

this should work:

def my_lc(m, n):
    return [list(range(m * i + 1, (i + 1) * m + 1)) for i in range(n)]

print(my_lc(3, 4))
# [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

or with itertools.count:

from itertools import count

def my_lc(m, n):
    c = count(1)
    return [list(next(c) for _ in range(m)) for _ in range(n)]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.