0

suppose I have a list as

mylist = [[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15],[16,17,18]]

If I want to add element-by-element then I can use logic as:

[x+y for x,y in zip(mylist[0],mylist[1],mylist[2],mylist[3],mylist[4],mylist[6]]

and it will give sum of columnwise elements. But the problem is , writing each index of mylist inside zip function is somewhat awkward and vague if mylist happens to be list of say 1000 lists and I need to do the element by element operation.

I tried putting loop inside the zip function but it doesn't work. So any idea for that??

It should work like

zip(for k in mylist) # or something else

Thanks

3
  • In your example, 'zip' will give you a list of 6-uples... Commented Oct 15, 2013 at 10:29
  • Your example has a syntax error and a logic error in it, just try to run it. But I think what you are looking for is zip(*mylist). Commented Oct 15, 2013 at 10:30
  • Look at 'reduce': docs.python.org/2/library/functions.html#reduce Commented Oct 15, 2013 at 10:30

2 Answers 2

3

To sum all the first elements, all the second elements and so on:

In [2]: [sum(k) for k in zip(*mylist)]
Out[2]: [51, 57, 63]

Note that each number in the output is a sum of len(mylist) numbers:

In [3]: zip(*mylist)
Out[3]: [(1, 4, 7, 10, 13, 16), (2, 5, 8, 11, 14, 17), (3, 6, 9, 12, 15, 18)]

The * operator unpacks mylist so that its items become separate arguments to zip.

Sign up to request clarification or add additional context in comments.

Comments

2

Another approach, that looks more obvious here, is to use the built-in map with sum along side zip on an unpacked list

>>> map(sum, zip(*mylist))
[51, 57, 63]

And if you are a fan of generators, the following might add some benefits

>>> from itertools import izip, imap
>>> list(imap(sum, izip(*mylist)))
[51, 57, 63]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.