1

Why does [0] * 5 create a list [0, 0, 0, 0, 0], rather than [[0], [0], [0], [0], [0]]?

Doesn't the * operator duplicate [0] 5 times resulting in [[0], [0], [0], [0], [0]]?

Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
hbprotoss
  • 1,385
  • 10
  • 27
  • possible duplicate of [Python list multiplication: \[\[...\]\]*3 makes 3 lists which mirror each other when modified](http://stackoverflow.com/questions/6688223/python-list-multiplication-3-makes-3-lists-which-mirror-each-other-when) – BrenBarn Aug 03 '12 at 02:32

4 Answers4

7

Just like math:

[0] * 5 = [0] + [0] + [0] + [0] + [0], which is [0, 0, 0, 0, 0].

I think people would be more surprised if [0] + [0] suddenly became [[0], [0]].

For strings, tuples, and lists, + is an append operator. This multiplication holds true for all of them.

Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
Max
  • 10,701
  • 2
  • 24
  • 48
2

Reading the Python docs for sequence types it seems that it is because [0] * 5 is shorthand for [0] + [0] + [0] + [0] + [0] (just as multiplication is in math a shorthand for addition; it works the same when "multiplying" lists).

Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
0

No, it multiplies elements and [0] list (just like mathematical set) has one element 0, not [[0]].

Edmon
  • 4,752
  • 4
  • 32
  • 42
  • In another word, + means add the elements in the operands into one list, rather than make two lists into elements of a new list? – hbprotoss Aug 03 '12 at 03:04
0

Use statement below to create [[0], [0], [0], [0], [0]]:

[[0]*1]*5

Note that the list you've mentioned above is a 2d list, so you must use * operator in right way. It means your list has 5 rows and 1 column.

Below is the real result: enter image description here