0

I'm prety new to python so my question might be basic but is there a way to change two variables at the same time when using a function. my problem is i currently use a double for loop to do so and it creates a lot of useless values. As we understand better by exemple, here is a rapidly crafted one:

results=[]
Q1=[1,2,3]
P1=[4,5,6]
def findcash(Q,P):
    r=Q/P
    results.append(r)
for i in Q1:
    for j in P1:
        findcash(i,j)

now you see my return vector will have values of 1/4 ;1/5; 1/6 ... where in reality i would like Q1 to change when P1changes so results=[1/4 2/5 3/6]

Cheers

2
  • You cannot alter a global variable in a function scope unless you declare it global there. Commented Apr 27, 2020 at 22:24
  • 1
    Sounds like you want to zip the lists Commented Apr 27, 2020 at 22:26

2 Answers 2

2

You can use the builtin zip

results = [Q/P for Q, P in zip(Q1, P1)]

which is kind of equivalent to this: (not really, but the idea is the same (you know - like a zipper))

for i in range(min(len(Q), len(P))):
     Q = Q1[i]
     P = P1[i]
     ...
Sign up to request clarification or add additional context in comments.

Comments

0
results=[]
Q1=[1,2,3]
P1=[4,5,6]
def findcash(Q,P):
    r=Q/P
    results.append(r)
for i,j in zip(Q1, P1):
  findcash(i,j)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.