Home > Back-end >  How to assemble nested-list elements
How to assemble nested-list elements

Time:12-16

def nested_list(nested):
for i in range (0, len(nested)):
    for k in range (0, len(nested)):
        print(nested[i][k], end = " ")

nested_list([[1,2,3],[4,5,6],[7,8,9]])

output : 1 2 3 4 5 6 7 8 9

İt is working. But when I change nested_list([[1,2,3,4],[5,6],[7,8,9,10]])like this I get an error. What is the best solution to fix this problem ?

CodePudding user response:

You get an error because your original code assumes "square" list (sublists of the same length like full list).

You need to change inner for loop to check for len of current sublist, not whole list:

def nested_list(nested):
    for i in range (0, len(nested)):
        for k in range (0, len(nested[i])): # check len of current sublist
            print(nested[i][k], end = " ")

CodePudding user response:

There is a fast way to do this:

nested_list = [[1,2,3],[4,5,6],[7,8,9]]
print(sum(nested_list, []))

The sum Python's built-in function can be used to "sum" (and in this case to concatenate) the elements in an iterable.

  • Related