2

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']
1
  • 1
    You are checking sublist[1] == search, i.e. if and only if second element of sublist is equal to search. Change it to search in sublist and it should be fine. Commented Sep 17, 2019 at 5:26

2 Answers 2

8

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

1 Comment

Thank you. It is working. May the force be with you.
1

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

9 Comments

Thank you. It is working. It is very clean and clear and well structure.
Is there any difference if my input data are surrounded by parentheses?
data = [('a','b'), ('a','c'), ('b','d'),('a','b')]
No, it will be same, except in the output you will see "Found it!('a', 'b')" instead of "Found it!['a', 'b']".
What about a tuple? I am always confused with [], {} or () or SET too.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.