Create a Python N list.

Asked 2 years ago, Updated 2 years ago, 38 views

The following N lists with Python

list1=[]

list2=[]

list3=[]

...

listN=[]

I'd like to make something. Write a for statement

for i in range(1,N+1):
    list%s=[] %i

If you do, the error can't assign to operator appears.

Is there any way?

python list

2022-09-21 14:54

1 Answers

Well, is that necessary? It is better to do as below.

D = {'list{}'.format(n):list() for n in range(1, 11)}
print(D)

{'list1': [], 'list2': [], 'list3': [], 'list4': [], 'list5': [], 'list6': [], 'list7': [], 'list8': [], 'list9': [], 'list10': []}

Of course, you can do as the questioner asks, but you need to use reflection. First, don't confuse the code written by the questioner with the code your computer understands.

Please refer to the sample below.

import sys
mod = sys.modules[__name__]
for n in range(1, 11):
    setattr(mod, 'list{}'.format(n), [])

print(list1)
print(list10)

[]
[]


2022-09-21 14:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.