-4

I need to make some lists with the contents of a list. Like a:

list=["One", "Two", " Three "]
for x in list:
     x = []

But it doesn't works because if I do:

list(One)

It didn't show the content of One, because One is not defined.

So, is it possible to create lists with content of other list?

Hayley Guillou
  • 3,953
  • 4
  • 24
  • 34

6 Answers6

5

We expected the output with three lists. One =[]; Two=[] and Three=[]

Use a dictionary:

i = ['One', 'Two', 'Three']
d = {} # empty dictionary
for n in i:
    d[n] = []

>>> print(d['One'])
[]
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
1

Are you looking for this?

list = []
for i in range(listLength):
    list.append([])

This would produce a list such as the following for a listLength of 3:

list = [[], [], []]
Vedaad Shakib
  • 739
  • 7
  • 20
0

Use dictionary comprehension

>>> l = ['One', 'Two', 'Three']
>>> {key: [] for key in l}
{'Three': [], 'Two': [], 'One': []}
0

I think using zip is better and easier.

list_ = ['One', 'Two', 'Three']
a = dict(zip(list_, [[] for _ in range(len(list_))]))
print a
#{'Three': [], 'Two': [], 'One': []}

zip can assign null list to each element of the list.

Burger King
  • 2,945
  • 3
  • 20
  • 45
-1

Are you looking to create a list of lists like the below?

One = [1,2,3]
Two = [4,5,6]
Three = [7,8,9]

list = [One,Two,Three]
Stanley
  • 2,798
  • 5
  • 22
  • 44
-2

Would something like this work for you?

>>> keys = ['one', 'two', 'three']
>>> for k in keys:
...     globals()[k] = []
...
>>> one
[]
>>> two
[]
>>> three
[]

also remember that list is a reserved word so not a good variable name

not that this is a good thing to do, but sounds like what you are asking for.

bcollins
  • 3,379
  • 4
  • 19
  • 35