Home > Mobile >  Tuple element to its own tuple and append item
Tuple element to its own tuple and append item

Time:05-08

I want to do this:

[("item1", "item2"), ("item3", "item4")]
# ->
[("item1", ("item2", True)), ("item3", ("item4", True))]

How can I do this? I have a list of tuples, and the second element in each tuple needs to be it's own tuple, and I need to append an element to the sub tuple.

CodePudding user response:

an option is to use a list-comprehension:

lst = [("item1", "item2"), ("item3", "item4")]
res = [(a, (b, True)) for a, b in lst]
print(res)  # [("item1", ("item2", True)), ("item3", ("item4", True))]

CodePudding user response:

You can use list comprehension to complete this:

material = [("item1", "item2"), ("item3", "item4")]
# ->
expected = [("item1", ("item2", True)), ("item3", ("item4", True))]

actual = [(elt[0], (elt[1], True)) for elt in material]
assert actual == expected

CodePudding user response:

Easy answer

lst = [("item1", "item2"), ("item3", "item4")]

new_lst = []

for f,s in lst:
    new_lst.append((f, (s, True)))
print(new_lst)

OUTPUT

[("item1", ("item2", True)), ("item3", ("item4", True))]

USING LIST COMPREHENSION

lst = [("item1", "item2"), ("item3", "item4")]
new_lst = [(f, (s, True)) for f,s in lst]

print(new_lst)

OUTPUT

[("item1", ("item2", True)), ("item3", ("item4", True))]

CodePudding user response:

Another way to accomplish this would be to use the map function.

This is what you could do:

def map_func(item):
    return (item[0], (item[1], True))

array = [("item1", "item2"), ("item3", "item4")]
new_array = list(map(map_func, array))

print(new_array) # [('item1', ('item2', True)), ('item3', ('item4', True))]

You could use lambda too (in order to shorten the code), like so:

new_array = list(map(lambda item: (item[0], (item[1], True)), array))
  • Related