0

I am wondering, how i can shorten this:

test = [1, 2, 3]
test[0] = [1, 2, 3]
test[1] = [1, 2, 3]
test[2] = [1, 2, 3]

I tried something like this:

test = [1[1, 2, 3], 2 [1, 2, 3], 3[1, 2, 3]]
#or
test = [1 = [1, 2, 3], 2 = [1, 2, 3], 3 = [1, 2, 3]] #I know this is dumb, but at least I tried...

But it's not functioning :|

Is this just me beeing stupid and trying something that can not work, or is there a proper Syntax for this, that I don't know about?

thefourtheye
  • 221,210
  • 51
  • 432
  • 478
encomiastical
  • 11
  • 1
  • 4

4 Answers4

4

The simplest way is

test = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]

But, if you want to have more number of lists to be created then you might want to go with list comprehension, like this

test = [[1, 2, 3] for i in range(100)]

This will create a list of 100 sub lists. The list comprehension is to create a new list and it can be understood like this

test = []
for i in range(100):
    test.append([1, 2, 3])

Note: Instead of doing test[0] = ..., you can simply make use of list.append like this

test = []
test.append([1, 2, 3])
...

If you look at the language definition of list,

list_display        ::=  "[" [expression_list | list_comprehension] "]"

So, a list can be constructed with list comprehension or expression list. If we see the expression list,

expression_list ::=  expression ( "," expression )* [","]

It is just a comma separated one or more expressions.

In your case,

1[1, 2, 3], 2[1, 2, 3] ...

are not valid expressions, since 1[1, 2, 3] has no meaning in Python. Also,

1 = [1, 2, 3]

means you are assigning [1, 2, 3] to 1, which is also not a valid expression. That is why your attempts didn't work.

thefourtheye
  • 221,210
  • 51
  • 432
  • 478
1

Your code: test = [1 = [1, 2, 3], 2 = [1, 2, 3], 3 = [1, 2, 3]] is pretty close. You can use a dictionary to do exactly that:

test = {1: [1, 2, 3], 2: [1, 2, 3], 3: [1, 2, 3]}

Now, to call test 1 simply use:

test[1]

Alternatively, you can use a dict comprehension:

test = {i: [1, 2, 3] for i in range(3)}
user
  • 4,960
  • 7
  • 46
  • 70
0

It's a list comprehension:

test = [[1, 2, 3] for i in range(3)]
Malik Brahimi
  • 15,933
  • 5
  • 33
  • 65
0

If you want, you can do this:

test = [[1,2,3]]*3
#=> [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
masaya
  • 314
  • 2
  • 7
  • 12