Iterating through a list:finding common values

python

#1

Hi, how do you iterate through and print out the values in a list within a list that are similar, such that they both have a common value?" e.g.[[“John”,“14”],[“Ben”,“14”]].In here the number, “14” appears in both list, so my question is how do you iterate through the list so that it prints out the two identical lists at same time when you input the number"14" as it appears in both lists.


Help to interpret in python
#2
members = [["John",14],["Ben",14]]

number = 14
matches = []
for item in members:
    if number in item:
        matches.append(item)

for item in matches:
    print (item)
['John', 14]
['Ben', 14]

#3

hi thanks for replying but it says invalid sytax for the variable number?


#4
[[“John”,“14”],[“Ben”,“14”]]

Is this the error:

Traceback (most recent call last):
  File "python", line 1
    members = [[“John”,“14”],[“Ben”,“14”]]
                     ^
SyntaxError: invalid character in identifier

If so it has to do with the smart quotes. Change your list to use standard quotes.

[["John",14],["Ben",14]]

#5

this is the error:
image


#6

this is a more clear image:
image


#7

I have fixed the problem, it was because I needed a close square bracket at the end of the list(stupid mistake) but thank you for helping, I really appreciate that.


#8

2 posts were split to a new topic: List that contains the people who’s age is equal or younger