Search code examples
pythonzip

How can I use zip function for this?


for i in range(2200):
    calculate_path(r_mercury, mercury_track, i)
    calculate_path(r_venus, venus_track, i)
    calculate_path(r_earth, earth_track, i)
    calculate_path(r_mars, mars_track, i)
    calculate_path(r_jupiter, jupiter_track, i)
    calculate_path(r_saturn, saturn_track, i)
    calculate_path(r_uranus, uranus_track, i)
    calculate_path(r_neptune, neptune_track, i)

This is the code, I would like to optimize it using zip, is there any way I can do that?

And the first And the first parameter of calculate_path is an int, second one is empty list, but I am appending values in function.


Solution

  • I would not call this optimizing since it doesn't improve anything, but here is a shorter implementation:

    r_planets = [r_mercury, r_venus, r_earth]
    planets_tracks = [mercury_track, venus_track, earth_track]
    
    for i in range(2200):
        for r_planet, planets_track in zip(r_planets, planets_tracks):
            calculate_path(r_planet, planets_track, i)
    

    Alternatively, with one less for loop (but still the same number of iteration anyway):

    import itertools
    
    r_planets = [r_mercury, r_venus, r_earth]
    planets_tracks = [mercury_track, venus_track, earth_track]
    
    for p, i in itertools.product(zip(r_planets, planets_tracks), range(2200)):
        r_planet = p[0] # can be remove
        planets_track = p[1] # can be remove
        calculate_path(r_planet, planets_track, i) # can be replace with calculate_path(p[0], p[1], i)