1

I have a function to process the list of tuples. What is the easiest way to include for loop inside the function itself? I am fairly new to python, trying to convert this in OOP function. Any help will be appreciated.

My current solution:

tups = [(1,a),(2,b),(5,t)]

def func(a,b):
    # do something for a and b
    return (c,d)

output = []
for x, y in tups:
    output.append(func(x,y))

output will be

[(c,d),(m,n),(h,j)]
2

3 Answers 3

1

I think map is more suitable for your use case

tups = [(1,"a"),(2,"b"),(5,"t")]

def func(z):
    # some random operation say interchanging elements
    x, y = z
    return y, x

tups_new = list(map(func, tups))
print(tups_new)

Output:

[('a', 1), ('b', 2), ('t', 5)]
Sign up to request clarification or add additional context in comments.

1 Comment

This was quick and easy. Thanks!
1

just write your loop in func:

tups = [(1,a),(2,b),(5,t)]

def func(tuples):
    for a, b in tuples:
        # do something for a and b
        result.append((c,d))
    return result

output = []
output.append(func(tups))

Comments

0

Just do this with list comprehensions:

tups = [(1,"a"),(2,"b"),(5,"t")]

print([(obj[1], obj[0]) for obj in tups])

# [('a', 1), ('b', 2), ('t', 5)]

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.