0

I have a list of a = [("apple", "red"), ("pear", "green"), ("orange", "orange"), ("banana", "yellow"), ("tomato", "red")]

I want to iterate through this list and if a[1] = "red", how do I append the whole tuple ("tomato", "red") and ("apple", "red") such that it will appear in b=[] list as b = [("tomato", "red), ("apple", "red")]?

5 Answers 5

8

Use a list comprehension

b = [tup for tup in a if tup[1] == "red"]
print(b)
[('apple', 'red'), ('tomato', 'red')]
Sign up to request clarification or add additional context in comments.

2 Comments

what if I want both the colour "red" and "green" to be appended into the tuple list?
@KimSuYu if tup[1] in ('red', 'green')
1

Just append the tuple:

In [19]: a = [("apple", "red"), ("pear", "green"), ("orange", "orange"), ("banana", "yellow"), ("tomato", "red"), ('avocado','green')]

In [20]: reds = []

In [21]: for pair in a:
    ...:     if pair[1] == 'red':
    ...:         reds.append(pair)
    ...:

In [22]: reds
Out[22]: [('apple', 'red'), ('tomato', 'red')]

However, it seems to me you might be looking for a grouping, which could conveniently be represented with a dictionary of lists:

In [23]: grouper = {}

In [24]: for pair in a:
    ...:     grouper.setdefault(pair[1], []).append(pair)
    ...:

In [25]: grouper
Out[25]:
{'green': [('pear', 'green'), ('avocado', 'green')],
 'orange': [('orange', 'orange')],
 'red': [('apple', 'red'), ('tomato', 'red')],
 'yellow': [('banana', 'yellow')]}

Comments

1

I second the list comprehension, you can even do it with the names of the things.

b = [(fruit, color) for fruit, color in a if color == "red"]

or if you wanna do it in a loop:

b = []
for fruit, color in a:
   if color == "red":
       b.append((fruit, color))

or if you wanna do multiple variations:

def fruitByColor(ogList, filterList):
    return ([(fruit, color) for fruit, color in ogList 
             if color in filterList])

fruitByColor(a, ["green", "red"])

Comments

0

You can create a dictionary of tuples with colors as keys and values as list of fruits as follows:

colors={}
for i in range(len(a)):
    if a[i][1] not in colors:
        colors[a[i][1]]=[a[i][0]]
    else:
        colors[a[i][1]].append(a[i][0])

Output:

{'green': ['pear'],
'orange': ['orange'],
'red': ['apple', 'tomato'],
'yellow': ['banana']}

Comments

0

Try this:

b = []
a = [("apple", "red"), ("pear", "green"), ("orange", "orange"), ("banana", "yellow"), ("tomato", "red")]
if a[1][1] == "red":
    b.append(("tomato", "red"))
    b.append(("apple", "red"))
print(b)

The a[1][1] accesses the second element in the array a and the second element of the tuple in that element

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.