0

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.

0

4 Answers 4

3

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))]
Sign up to request clarification or add additional context in comments.

2 Comments

This answer unpacks the elements of lst. This is smart.
i prefer this to indexing later (as you did). but that's ok as well! +1
1

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

Comments

1

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

Comments

0

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

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.