6x2KYqRT
6x2KYqRT

Reputation: 37

Tuple element to its own tuple and append item

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.

Upvotes: 0

Views: 84

Answers (4)

HerrAlvé
HerrAlvé

Reputation: 645

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))

Upvotes: 0

hiro protagonist
hiro protagonist

Reputation: 46849

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))]

Upvotes: 3

Sharim09
Sharim09

Reputation: 6214

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))]

Upvotes: 1

Floh
Floh

Reputation: 909

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

Upvotes: 1

Related Questions