user11589714
user11589714

Reputation:

Search list in list written in Python

I have modified a simple search list in list (codes borrowed from another site) but unable to capture all the relevant information.

INPUT FILE :

data = [['a','b'], ['a','c'], ['b','d'],['a','b']]

I am searching the whole list with a 'b' in it but my algorithm only captures anything ending with a 'b'. I could not capture all 'b' whether it starts in Index(0) or Index(1).

data = [['a','b'], ['a','c'], ['b','d'],['a','b']]
search = 'b'
for sublist in data:
    if sublist[1] == search:
        print("Found it!" + str(sublist))

Below is the OUTPUT but it is missing ['b','d']. Could someone help please?

Found it!['a', 'b']
Found it!['a', 'b']

Upvotes: 2

Views: 98

Answers (2)

han solo
han solo

Reputation: 6590

Just use in for membership check like,

>>> data = [['a','b'], ['a','c'], ['b','d'],['a','b']]
>>> for sub in data:
...   if 'b' in sub:
...     print(sub)
... 
['a', 'b']
['b', 'd']
['a', 'b']

Upvotes: 8

Dipen Dadhaniya
Dipen Dadhaniya

Reputation: 4630

Try:

data = [['a','b'], ['a','c'], ['b','d'],['a','b']]
search = 'b'
for sublist in data:
    # Edited this part
    if search in sublist:
        print("Found it!" + str(sublist))

Output:

Found it!['a', 'b']
Found it!['b', 'd']
Found it!['a', 'b']

Upvotes: 1

Related Questions