Multiplication Operator in Python


The Python way of initializing a list can be clearly expressed as the multiplication operator: * for example,

# an array of ten integers, which are all initialized to zeros
arr = [0] * 10 

However, if someone may write the following to create ten random integers, which may not be expected.

#!/usr/bin/env python
from random import *
seed()
# all numbers are identical, which is only one random number
arr = [randint(0, 10)] * 10 

The correct way of doing this is to use the natural language expression.

#!/usr/bin/env python
from random import *
seed()
arr = [randint(0, 10) for x in xrange(0, 10)]

The multiplication can be easily used to create duplicated elements in a list, however, it cannot be used to invoke the same function many times i.e. the following will not work.

def hello():
    print "hello"
hello() * 5 # will not work

It will throw the following message:

Traceback (most recent call last):
  File "C:\Python27\test.py", line 3, in module
    hello() * 10
TypeError: unsupported operand type(s) for *: "NoneType" and "int"
</module>

Because Python will treat hello() as a function that returns a number and it expects a return-val from the function. The workaround is to use the following.

def hello():
    print "hello"

def run(x, t):
    for y in xrange(0, t):
        x()

run(hello, 10) # prints "hello" ten times

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
282 words
Last Post: Dis Module in Python
Next Post: Math Example using Windows Batch Script

The Permanent URL is: Multiplication Operator in Python

Leave a Reply