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...
add two lists
Page 1 of 13 Replies  9913 Views  Last Post: 06 February 2011  09:46 PM
Replies To: add two lists
#2
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.
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.
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.
#3
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)
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)
#4
Re: add two lists
Posted 06 February 2011  09:46 PM
Umm...you need to print the list...you can't expect it to just appear...
Page 1 of 1
