473,398 Members | 2,125 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

list*list

There must be a better way to multiply the elements of one list by
another:

a = [1,2,3]
b = [1,2,3]
c = []
for i in range(len(a)):
c.append(a[i]*b[i])
a = c
print a
[1, 4, 9]

Perhaps a list comprehension or is this better addressed by NumPy?

Thanks,

jab

May 1 '06 #1
10 1298
> There must be a better way to multiply the elements of one list by
another:

a = [1,2,3]
b = [1,2,3]
c = []
for i in range(len(a)):
c.append(a[i]*b[i])
a = c
print a
[1, 4, 9]

Perhaps a list comprehension or is this better addressed by NumPy?

First of all: it's considered bad style to use range if all you want is a
enumeration of indices, as it will actually create a list of the size you
specified. Use xrange in such cases.

You can use a listcomp like this:

c = [a[i] * b[i] for i in xrange(len(a))]

But maybe nicer is zip:

c = [av * bv for av, bv in zip(a, b)]

And if lists get large and perhaps multidemnsional, numpy certainly is the
way to go.

Diez

May 1 '06 #2
> There must be a better way to multiply the elements of one list by
another:

a = [1,2,3]
b = [1,2,3]
c = []
for i in range(len(a)):
c.append(a[i]*b[i])
a = c
print a
[1, 4, 9]

Perhaps a list comprehension or is this better addressed by NumPy?


a = [1,2,3]
b = [1,2,3]
c = [q*r for q,r in zip(a,b)]

seems to do the trick for me.

-tim


May 1 '06 #3
"Diez B. Roggisch" <de***@nospam.web.de> wrote in message
news:4b*************@uni-berlin.de...
it's considered bad style to use range if all you want is a
enumeration of indices, as it will actually create a list of the size you
specified. Use xrange in such cases.


I'm pretty sure this distinction goes away in 2.5.
Cheers,
Alan Isaac
May 1 '06 #4
David Isaac wrote:
it's considered bad style to use range if all you want is a
enumeration of indices, as it will actually create a list of the size you
specified. Use xrange in such cases.


I'm pretty sure this distinction goes away in 2.5.


3.0.

and for short sequences, it doesn't really matter much in the 2.X series.
it's definitely not "bad style" to use range instead of xrange for a ten to,
say, 1000 item loop.

(it's not always the most efficient thing to do, though, but that's
another story).

</F>

May 1 '06 #5
> and for short sequences, it doesn't really matter much in the 2.X series.
it's definitely not "bad style" to use range instead of xrange for a ten
to, say, 1000 item loop.


You and me are aware of that - but I figured the OP wasn't. And just the
other day somebody on de.c.l.py wondered about the memory consumption of
his little script that contained a range(9000000) which he used for a loop.

And as in the case of a "for in" one can't even access the list produced by
range() and thus there is virtually no difference to xrange, I'd consider
it a code smell if it's used there - why creating an object you don't use
when you can't even get a reference to it?

Diez
May 1 '06 #6
Diez wrote:
First of all: it's considered bad style to use range if all you want is a
enumeration of indices, as it will actually create a list of the size you
specified. Use xrange in such cases. But maybe nicer is zip:
c = [av * bv for av, bv in zip(a, b)]


By your logic, shouldn't it also be "bad style" to create an
unnecessary list with zip instead of using izip?

-Mike

May 1 '06 #7
Klaas schrieb:
Diez wrote:
First of all: it's considered bad style to use range if all you want is a
enumeration of indices, as it will actually create a list of the size you
specified. Use xrange in such cases.

But maybe nicer is zip:
c = [av * bv for av, bv in zip(a, b)]


By your logic, shouldn't it also be "bad style" to create an
unnecessary list with zip instead of using izip?


Yep. I always forget about the itertools. And then of course we'd go for
an generator expression, won't we?
Diez
May 1 '06 #8
BBands wrote:
There must be a better way to multiply the elements of one list by
another:
[snipped]
Perhaps a list comprehension or is this better addressed by NumPy?
If you have a large amount of numerical code, it is definetly better to
use numpy, since it is intended just for that purpose:
import numpy
a = numpy.array([1, 2, 3])
b = numpy.array([1, 2, 3])
c = a * b
c array([1, 4, 9])

Otherwise, you can use the builtin function map and functions in the
operator module:
import operator
a = [1, 2, 3]
b = [1, 2, 3]
c = map(operator.mul, a, b)
c [1, 4, 9] d = map(operator.add, a, b)
d

[2, 4, 6]
Thanks,

jab


Ziga

May 1 '06 #9
Very useful comments... Thanks to all!

Once again this community has demonstrated why Python is THE language.

jab

May 3 '06 #10
Ziga Seilnach:
c = map(operator.mul, a, b)


Usually I like map a lot, but this time for me the l.c. version is a
bit simpler to understand (even if it's longer, and maybe slower too):
from operator import mul
from itertools import izip
a = [1, 2, 3]
b = [4, 5, 6]
map(mul, a, b) [4, 10, 18] [arow * brow for arow, brow in izip(a, b)]

[4, 10, 18]

Bye,
bearophile

May 3 '06 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: massimo | last post by:
Hey, I wrote this program which should take the numbers entered and sort them out. It doesnąt matter what order, if decreasing or increasing. I guess I'm confused in the sorting part. Anyone...
10
by: Kent | last post by:
Hi! I want to store data (of enemys in a game) as a linked list, each node will look something like the following: struct node { double x,y; // x and y position coordinates struct enemy...
24
by: Robin Cole | last post by:
I'd like a code review if anyone has the time. The code implements a basic skip list library for generic use. I use the following header for debug macros: /* public.h - Public declarations and...
4
by: JS | last post by:
I have a file called test.c. There I create a pointer to a pcb struct: struct pcb {   void *(*start_routine) (void *);   void *arg;   jmp_buf state;   int    stack; }; ...
3
by: chellappa | last post by:
hi this simple sorting , but it not running...please correect error for sorting using pointer or linked list sorting , i did value sorting in linkedlist please correct error #include<stdio.h>...
0
by: drewy2k12 | last post by:
Heres the story, I have to create a doubly linked list for class, and i have no clue on how to do it, i can barely create a single linked list. It has to have both a head and a tail pointer, and...
10
by: AZRebelCowgirl73 | last post by:
This is what I have so far: My program! import java.util.*; import java.lang.*; import java.io.*; import ch06.lists.*; public class UIandDB {
0
by: Atos | last post by:
SINGLE-LINKED LIST Let's start with the simplest kind of linked list : the single-linked list which only has one link per node. That node except from the data it contains, which might be...
12
by: kalyan | last post by:
Hi, I am using Linux + SysV Shared memory (sorry, but my question is all about offset + pointers and not about linux/IPC) and hence use offset's instead on pointers to store the linked list in...
7
by: QiongZ | last post by:
Hi, I just recently started studying C++ and basically copied an example in the textbook into VS2008, but it doesn't compile. I tried to modify the code by eliminating all the templates then it...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.