3 Replies - 10642 Views - Last Post: 06 February 2011 - 09:46 PM Rate Topic: -----

#1 naufilah  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 17-May 10

add two lists

Posted 06 February 2011 - 09:15 PM

HI there,
this problem seems to be easy but i cant seem to find a solution to it.

list1 = [1,2,3]
list2 = [4,5,6]
# result should be [5,7,9]

i have tried coming up with the following code but,theres still a error.

def add2lists(11, l2):
list_1 = [1,2,3]
list_2 = [4,5,6]


if __name__ == "__main__":



may i know how to solve this and come up with the result.
someone help out...

Is This A Good Question/Topic? 0
  • +

Replies To: add two lists

#2 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2876
  • View blog
  • Posts: 11,050
  • Joined: 15-July 08

Re: add two lists

Posted 06 February 2011 - 09:30 PM

This is as simple as doing a list comprehension and using the zip function. What you can do is iterate over both lists and sum up the result of the two numbers. The zip function takes two lists and returns a list a tuples.

list3 = [(x + y) for x, y in zip(list1, list2)]



Thus, for the first number, the zip() method returns (1, 4) which, when added is 5. Then the next tuple returned is (2,5), which when added is 7. Thus you are making a single list out of two.
Was This Post Helpful? 0
  • +
  • -

#3 naufilah  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 17-May 10

Re: add two lists

Posted 06 February 2011 - 09:45 PM

Hi there,

I have tried adding the code to the code like this...and when i run the code,theres no error displayed at the same time,theres no output.pls look back into my codes and help me out.Thanks lots!


def add2lists(l1, l2):
list_1 = [1,2,3]
list_2 = [4,5,6]
list3 = [(x + y) for x, y in zip(list_1, list_2)]


if __name__ == "__main__":
add2lists(11, 12)
Was This Post Helpful? 0
  • +
  • -

#4 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2876
  • View blog
  • Posts: 11,050
  • Joined: 15-July 08

Re: add two lists

Posted 06 February 2011 - 09:46 PM

:code:

Umm...you need to print the list...you can't expect it to just appear...
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1