I'll do my best to explain my concern.

This problem is a practice activity for me as I learn python.

How could I check one by one if the element of the first lists is bigger than the element on the second lists then subtract?

Example:

# inputted values
list1 = [50,40,90,30]
list2 = [40,50,40,20]


# desired output:
output = [10,40,50,10]

4 Answers

3
Joshua Fox On

You needs some real lists, not just four variables. Then do this.

list1=[50,40, 90, 30]
list2=[40, 50, 40, 20]
output=[p1-p2 if p1>p2 else p1 for (p1, p2) in zip(list1, list2)]
print(output) #==> [10, 40, 50, 10] 
1
Devesh Kumar Singh On

You essentially need to iterate over both lists together and compare each element pairwise, then the output will be element from list1 if it is smaller than the element in list2, or else the output will be the difference of list2's element and list1's element

Two ways to achieve this

  1. List-comprehension by simultaneously iterating on both lists
list1 = [50,40,90,30]
list2 = [40,50,40,20]

print([list1[idx] if list1[idx] < list2[idx] else list1[idx] - list2[idx] for idx in range(len(list1))])

Output is [10, 40, 50, 10]

  1. List-comprehension by iterating on the iterator created by zipping both lists together
list1 = [50,40,90,30]
list2 = [40,50,40,20]

print([item1 if item1 < item2 else item1 - item2 for item1, item2 in zip(list1, list2)])

Output is [10, 40, 50, 10]

0
YHoffman On

I don't understand why we are all answering a new python dev with list comps, I believe that a newly minted dev should first start with an easier syntax, and let them learn about the python features (like list comps) that can improve their code.</rant>
To answer your question,
1. you can iterate multiple lists of the same length using python's built-in zip which takes multiple iterables as arguments and returns a tuple with the current element of each iterator at the same index, the function works like this;

list1 = [50,40,90,30]
list2 = [40,50,40,20]

for i1, i2 in zip(list1, list2):
    print(i1, i2)

# result
50, 40
40, 50
90, 40
30, 20

and then 2. you can start adding your logic at each iteration;

# if you want to store the results use the results list.
results = []
list1 = [50,40,90,30]
list2 = [40,50,40,20]

for i1, i2 in zip(list1, list2):
    if i1 > i2:
        result.append(i1 - i2)
        # or if you don't need to store the results, just use...
        print(i1 - i2)
    else:
        result.append(i1)
        # same here...
        print(i1)

# result
10
40
50
10
# results == [10, 40, 50, 10]
0
Eric Duminil On

It might be an overkill to use numpy but the syntax is clear and concise:

>>> import numpy as np
>>> a1 = np.array([50, 40, 90, 30])
>>> a2 = np.array([40, 50, 40, 20])
>>> np.where(a1 >= a2, a1 - a2, a1)
array([10, 40, 50, 10])