Home > Back-end >  Python - Write a function with x sublists, y elements in each sublist and each element equals to z
Python - Write a function with x sublists, y elements in each sublist and each element equals to z

Time:10-01

Write a function that takes three arguments (x, y, z) and returns a list containing x sublists (e.g. [[], [], []]), each containing y number of item z.

x Number of sublists contained within the main list. y Number of items contained within each sublist. z Item contained within each sublist.

e.g. x = 3, y = 2, z = 3 output: [[3, 3], [3, 3], [3, 3]]

CodePudding user response:

def f(x, y, z):
    return [[z for n in range(y)] for n in range(x)]

..or in a more readable manner :

def f(x, y, z):
    sub_list = [z for n in range(y)]
    return [sub_list for n in range(x)]

CodePudding user response:

list = []
for i in range(x):
    list.append([])
    for j in range(y):
        list[i][j].append(z)
  • Related