Home > Blockchain >  How to print each element of a list on a new line in a nested list
How to print each element of a list on a new line in a nested list

Time:11-15

I wanted to print each individual element of a list that's in nested list. it should also print symbols to show where the different lists end. There are only going to be 3 lists total in the big list.

For Example,

list1 = [['assign1', 'assign2'], ['final,'assign4'], ['exam','study']]

Output should be:

######################
assign1
assign2
######################
----------------------
final
assign4
----------------------
*************************
exam
study
*************************

I know that to print an element in a normal list it is: for element in list1: print element

I am unaware of what steps to take next.

CodePudding user response:

You can create another for loop around the one you know how to create. So:

for list2 in list1:
  # print some stuff here
  for word in list2:
    print(word)
  # print some more stuff

CodePudding user response:

Assuming that there is a single nesting level.

symbols = "#-*"
list1 = [['assign1', 'assign2'], ['final', 'assign4'], ['exam','study']]
for i, element in enumerate(list1):
    symbol = symbols[i%len(symbols)]
    print(symbol*20)
    print('\n'.join(element))
    print(symbol*20)

CodePudding user response:

list1 = [["assign1", "assign2"], ["final","assign4"], ["exam","study"]]

for x in list1:
    for list2 in x:
        print(list2)
    print("\n")
  • Related