user2979268
user2979268

Reputation: 15

Automatic creation of lists

I would like to create a code where I could create (n) numbers of lists automatically without creating them one by one. I tried this example, where I wanted to get five lists named "my_list" automatically where every list has assigned ten numbers from 0 to 9 (for example).

for i in range(1,6):
    ("my_list_"+str(i)) = []
    for j in range(10):
        ("my_list_"+str(i)).append(j)

The message is: "SyntaxError: can't assign to operator"

This is just an example, the real problem is how to get the lists automatically without creating them one by one. Is possible to do this in Python? Thank you

Upvotes: 0

Views: 1261

Answers (5)

tripleee
tripleee

Reputation: 189397

The normal, regular way to handle this sort of requirement is to keep the keyed lists in a dictionary, not as variable names with a suffix.

my_list=dict()
for i in range(1,6):
    my_list[i] = []
    for j in range(10):
        my_list[i].append(j)

Upvotes: 1

Nafiul Islam
Nafiul Islam

Reputation: 82470

Using a function:

>>> auto_list = lambda n: [[] for _ in range(n)]
>>> auto_list(10)
[[], [], [], [], [], [], [], [], [], []]

If you wish for every list to be generated with say random numbers:

from random import randint


def auto_list(n):
    return [[randint(0, 100) for _ in range(5)] for _ in range(n)]


print auto_list(10)

Returns:

[[86, 33, 82, 28, 20],
 [13, 89, 22, 8, 73],
 [83, 44, 58, 71, 21],
 [66, 54, 41, 24, 8],
 [74, 98, 89, 53, 40],
 [63, 83, 13, 72, 68],
 [51, 55, 61, 36, 34],
 [38, 72, 95, 58, 82],
 [80, 16, 10, 44, 22],
 [9, 65, 84, 14, 91]]

Upvotes: 0

user2953680
user2953680

Reputation: 594

n = 40
my_lists = []


for i in range(1,40):
    my_lists.append([])

for list in my_lists:
    list.append(3)

Upvotes: 0

Sweeney Todd
Sweeney Todd

Reputation: 880

What you are doing here is that, you are trying to assign a list to a string. You cannot do that. If you need to create a lot of lists, first create another single list to store them all. Like this:

my_lists = []
for i in range(1,6):
    new_list = []
    for j in range(10):
        new_list.append(j)
    my_lists.append(new_list)

If you don't like this and want to reach these lists from a global scope using a variable name like my_list_3, you can try a little trick like this:

for i in range(1,6):
    globals()["my_list_"+str(i)] = []
    for j in range(10):
        globals()["my_list_"+str(i)].append(j)

print my_list_3

This will print [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Upvotes: 0

stranac
stranac

Reputation: 28236

You can easily create a list of lists using a list comprehensions:

my_lists = [range(10) for _ in xrange(5)]

Upvotes: 0

Related Questions