I have two lists:
A = [1, 2, 3, 4, 5]
B = [6, 7, 8, 9, 10]
And I need to be able to find the sum of the nth terms from both lists i.e. 1+6, 2+7, 3+8 etc
Could someone please tell me how to refer to items in both lists at the same time?
I read somewhere that I could do Sum = a[i] + b[i] but I’m not convinced on how that would work.
If you know the lists will be the same length, you could do this:
In Python 2, you might want to use
xrangeinstead ofrangeif your lists are quite large. I think that’s an explicit, simple, readable, obvious way to do it, but some might differ.If the lists might be different lengths, you have to decide how you want to handle the extra elements. Let’s say you want to ignore the extra elements of whichever list is longer. Here are three ways to do it:
The downside of using
zipis that it will allocate a list of tuples, which can be a lot of memory if your lists are already large. Usingfor i in xrangewith subscripting won’t allocate all that memory, or you can useitertools.izip:If you instead want to pretend the shorter list is padded with zeros, using
itertools.izip_longestis the shortest answer:or