Kevin Liu
Kevin Liu

Reputation: 83

Multiplying Elements in a List in Python

Say I have a list

alist = [6, 6, 6, 3, 1]

And I want to multiply every element in the list by 4 and return

alist = [24, 24, 24, 12, 4]

My current approach is to iterate through the list and multiply each element, just like:

for i in range(len(alist)):
    alist[i] = alist[i] * 4

Which is very inefficient, because once the first 6*4 is calculated, it's redundant to calculate it again for the second and third sixes. When I'm doing contest problems, it always exceeds the time limit once the numbers get large.

Is there a way to do the same multiplication process that doesn't calculate the same thing over and over again?

Upvotes: 1

Views: 585

Answers (6)

Akshay Kathpal
Akshay Kathpal

Reputation: 445

Good question use the inbuilt method append() in the python suppose in your case it is like Given list is like aList = [6, 6, 6, 3, 1] then use


b=List()


for i in alist:


    b.append(i*4)

print b #new list will take the result

Upvotes: 0

ammy
ammy

Reputation: 648

you can do like simple in list comprehension.

alist = [6,6,6,3,1] result = [x*4 for x in alist] print result

Upvotes: 0

fafl
fafl

Reputation: 7385

You could use a memoized function, which means that it can look up old results. For multiplication this might not help much, but for more complicated operations it can improve performance a lot.

cached_results = {}
def calc(a, b):
    if (a, b) not in cached_results:
        cached_results[(a, b)] = a*b
    else:
        print "already calculated value for (%s, %s)" % (a, b)
    return cached_results[(a, b)]

alist = [6, 6, 6, 3, 1]
print [calc(x, 4) for x in alist]

Upvotes: 2

AKS
AKS

Reputation: 19811

I am not sure if multiplication is what you would like to optimize here. Instead, use list comprehension:

alist = [n * 4 for n in alist]

Or, use map

alist = map(lambda n: n * 4, alist)

It is also recommended in Python Wiki on Performance Tips:

List comprehensions were added to Python in version 2.0 as well. They provide a syntactically more compact and more efficient way of writing the above for loop.

Upvotes: 1

zipa
zipa

Reputation: 27869

Interesting question, could this be what you are looking for:

alist = [6,6,6,3,1]

adict = {a: a*4 for a in set(alist)}

alist = [adict[a] for a in alist]

Upvotes: 1

elzell
elzell

Reputation: 2306

For longer lists a numpy array could be a better choice:

anarray = numpy.array([6,6,6,3,1])
anarray *= 4

I am quite sure that any kind of lookup to make sure that you don't do the same multiplication twice takes longer than actually doing the multiplication once more.

Upvotes: 1

Related Questions