Home > Enterprise >  Print some of list by for in python
Print some of list by for in python

Time:11-24

I have 4 lists and I want to print them, but it returns name of list.

list1 = ["a", "b", "c", "d"]
list2 = ["a", "b", "c"]
list3 = ["a", "b"]
list4 = ["a"]

for i in range(1,5):
    print(list[i])

It shows:

list[1]
list[2]
list[3]
list[4]

I need, for example ["a", "b", "c", "d"] for list1.

CodePudding user response:

You could make a list of lists if you want to print them like you are trying to do:

list1 = [
    ["a", "b", "c", "d"],
    ["a", "b", "c"],
    ["a", "b"],
    ["a"]
]

for i in range(len(list1)):
    print(list1[i])

CodePudding user response:

Variables don't work that way. If you need a similar kind of approach, you can use a dictionary.

dict_ = {
    "list1" : ["a", "b", "c", "d"],
    "list2" : ["a", "b", "c"],
    "list3" : ["a", "b"],
    "list4" : ["a"],
}

for i in range(1, 5):
    print(dict_["list" str(i)])

CodePudding user response:

if you want to print them in a loop, you need to put them in a "container" first (the container is noting but a list of its own).

list1 = ["a", "b", "c", "d"]
list2 = ["a", "b", "c"]
list3 = ["a", "b"]
list4 = ["a"]

container = [list1, list2, list3, list4]
for list in container:
    print(list)
  • Related