the_martian the_martian - 2 months ago 14
Python Question

List division between list

I have this code that generates two lists. One list goes from

1-30
and the other goes from
30-1
. How can divide each element of
some_list2
by each element of
some_list
. It would be something like this:
1/30
,
2/29
, an so on. I was thinking about storing each division value in a new list -- one division, one new element.

Here is what I have:

some_list = []
some_list2 = []

for i in reversed(range(1, 31)):
a = i
some_list.append(a)
for x in range(1,31):
b = x
some_list2.append(b)


I tried dividing one list by another as a whole, and I looked at a separate for loop for division, but I am stuck. I am doing this for practice by the way.

Answer

You can do this with a list comprehension by ziping the lists together, unpacking the tuple elements and dividing:

r = [i/j for i,j in zip(some_list2, some_list)]

this essentially creates tuples of (some_list2[i], some_list[i]) values, assigns them to i and j and then performs the division.

r is now a list holding the results:

print(r)
[0.03333333333333333,
 0.06896551724137931,
 0.10714285714285714,
 0.14814814814814814,
 0.19230769230769232,
 ...
 4.166666666666667,
 5.2,
 6.75,
 9.333333333333334,
 14.5,
 30.0]

Alternatively, you could also do this in a functional fashion, with map and truediv from the operator module:

from operator import truediv

r = list(map(truediv, some_list2, some_list))

truediv is a callable form of the '/' operator and is defined for usages such as this one. map will take elements from some_list2 and some_list and apply them to the truediv function; wrapping in a list call is done to expand the map result to a list.

Comments