0

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.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
the_martian
  • 632
  • 1
  • 9
  • 21
  • 1
    For the record, the code you have written could be simplified to `some_list = list(range(1, 31))`, `some_list2 = some_list[::-1]`. You're performing redundant work even if you must build by iterating and `append`ing (assigning to `a` before `append`ing is silly, when you could just `append` `i` directly). – ShadowRanger Sep 24 '16 at 15:41

1 Answers1

2

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.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253