0

Lists addition

Why does nums=[1,2,3] print(nums+[4,5,6]) Does not print 5,7,8? Instead it does 1,2,3,4,5,6

14th Aug 2016, 1:46 PM
Ryu
Ryu - avatar
5 Respostas
+ 1
The + operator on list-type collections (e.g., lists, strings) means "concatenation". When you concatenate two or more lists, you obtain a new list composed by their elements in the same order you expressed the concatenation. Thus: [1, 2, 3] + [4, 5, 6] gives you [1, 2, 3, 4, 5, 6] If you want to obtain a more "algebraic" result you have to consider using NumPy or implement a new class that wraps lists and overloads the __add__ method.
14th Aug 2016, 4:29 PM
MAP91
+ 1
because you are doing operation on lists not on integer variable !
14th Aug 2016, 5:08 PM
Jayvardhan Deshmukh
Jayvardhan Deshmukh - avatar
0
you're telling your pc to print the list nums First (1,2,3) and then to print the list 4,5,6 so the result is 1,2,3,4,5,6
14th Aug 2016, 2:03 PM
Jonas
0
raw.input() might work as in some programs it adds all the values in the list and gives the sum as result
24th Aug 2016, 2:09 PM
aditi saralaya
aditi saralaya - avatar
0
Basically + operator over 2 list will just append the content of the second list, by this way it jus creates and does not change original list until and unless we mention. Also extend() is a built in function that does the same job, but it changes the list upon which it is called.For example: list1 = [1, 2, 3] list2 = [4, 5, 6] list1.extend(list2) # will change the list1 now print(l1) #[1,2,3,4,5,6] If you want to add each element on the list to another list's corresponding values, you should make use map function like this list1 = [1, 2, 3] list2 = [4, 5, 6] print(map(lambda x,y: x+y, list1, list2)) # this will print # [5, 7, 9]
2nd Sep 2016, 2:46 AM
arvindh
arvindh - avatar