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)]
Sociopath
  • 13,068
  • 19
  • 47
  • 75
MikeCode
  • 91
  • 11
  • https://stackoverflow.com/questions/1663807/how-to-iterate-through-two-lists-in-parallel https://stackoverflow.com/questions/8372399/zip-with-list-output-instead-of-tuple https://stackoverflow.com/questions/10867882/tuple-unpacking-in-for-loops –  Jan 22 '20 at 04:22
  • 1
    What is the issue, exactly? _What is the easiest way to include for loop inside the function itself?_ Are you asking how to write a for loop? – AMC Jan 22 '20 at 04:29

3 Answers3

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))
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)]
Sociopath
  • 13,068
  • 19
  • 47
  • 75
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)]
funnydman
  • 9,083
  • 4
  • 40
  • 55