PIngu
PIngu

Reputation: 95

Resolve a tuple Return object in python

I am wanting to replace the elements of an existing list via mapping function of python. That is to say my program iterates through a list in python and replaces the elements of the list with one or more individual strings and lists.

state = ["a", "b", "c"]

def process(char):
  if char == "b":
    return ("x", "y")
  elif char == "c":
    return ("p",["q", "r"])
  else:
    return char

list(map(process, state))

output = ["a", ("x", "y"), ("p", ["q", "r"])]

But my problem area is that sometimes i chain return objects (here strings), so naturally they tend to be tuples. I want to replace an element within the list with the elements of a tuple rather that the actual tuple. Is there an easy way of dumping tuple elements so to speak.

Expected output is

output = ["a", "x", "y", "p", ["q", "r"]]

Note that the tuple objects are emptied out to replace the mapped individual element in my expected output. Whereas the list objects are preserved.

So is there someway to empty the elements of tuple such that all chained elements are returned rather than the actual tuple. Kindly suggest even if some other data type that may suit my use case.

My original program has objects in place of chars here. I felt that this abstract representation is a close resemblance microcosm of my actual research model.

Upvotes: 0

Views: 325

Answers (2)

lnogueir
lnogueir

Reputation: 2085

With := operator added in Python 3.8 you could do this:

state = ["a", "b", "c"]

def process(char):
  if char == "b":
    return "x", "y"
  elif char == "c":
    return "p", ["q", "r"]
  else:
    return char,

output = [
    p[idx] for s in state 
    if (p := process(s)) 
    for idx in range(len(p))
]

output # ['a', 'x', 'y', 'p', ['q', 'r']]

Upvotes: 0

Hajny
Hajny

Reputation: 79

This should work using .extend():

extended_list = []

for char in state:
    extended_list.extend(process(char))

print(extended_list)

>> ['a', 'x', 'y', 'p', ['q', 'r']]

Upvotes: 1

Related Questions