-6

I've the following code in python:

P = [0] * (6)

What am I doing here? Am I multiplying an array and a number? What is the result?

I saw this topic: What does asterisk * mean in Python?

But I guess it's not related.

Community
  • 1
  • 1

4 Answers4

2

The operators in Python are magic. They invoke special methods depending on the class of the operand. In this case a special method called __mul__ is called from the list class, since a list object is on the left-side.

In the case of a list, the list is repeated by the number of times given on the right (the parentheses are meaningless in this case). Tuple and string (str) objects can be multiplied in a similar way.

If you want to see what the special methods are, and their corresponding operators, see the operator module documentation.

By the way, you use the term array, which is understandable coming from other languages. However [0] does not create an array, but a list object. That might sound like semantics, but arrays do exist in python, but they have a specialised use. There is an array module in the standard library, and the numpy module also has arrays, see here. For everyday use though, list is the norm.

cdarke
  • 42,728
  • 8
  • 80
  • 84
1

if you run the code [0] * (6) you get [0, 0, 0, 0, 0, 0]. Similarly, if you run [1,2,3] * (6) you get [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]. So the asterisk is repeating/multiplying the list.

Mainul Islam
  • 1,196
  • 3
  • 15
  • 21
0

You're making, and concatenating, six copies of the list. I.e. [0] * 6 == [0, 0, 0, 0, 0 ,0]

Batman
  • 8,571
  • 7
  • 41
  • 80
-2

Snarky answer. Sorry but I cant help myself... this would have been so much less work then posting here!!!!

Heres a screencaputre of me finding the answer by typing 15 characters.

[temp548@compute-0-96 CUDA]$ python
Python 2.4.3 (#1, Sep 21 2011, 19:55:41)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-51)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> [0] * 6
[0, 0, 0, 0, 0, 0]
>>>
gbtimmon
  • 4,238
  • 1
  • 21
  • 36