In this article, we’ll take a look at how we can find a string in a list in Python. There are various approaches to this problem, from the ease of use to efficiency. We can use Python’s in operator to find a string in a list in Python. This takes in two operands Here, We can directly use this operator in the following way:Using the ‘in’ operator
a
and b
,
and is of the form:ret_value
is a boolean, which evaluates to True
if a
lies inside b
, and False
otherwise.a = [1, 2, 3]
b = 4
if b in a:
print['4 is present!']
else:
print['4 is not present']
Output
We can also convert this into a function, for ease of use.
def check_if_exists[x, ls]: if x in ls: print[str[x] + ' is inside the list'] else: print[str[x] + ' is not present in the list'] ls = [1, 2, 3, 4, 'Hello', 'from', 'AskPython'] check_if_exists[2, ls] check_if_exists['Hello', ls] check_if_exists['Hi', ls]
Output
2 is inside the list Hello is inside the list Hi is not present in the list
This is the most commonly used, and recommended way to search for a string in a list. But, for illustration, we’ll show you other methods as well.
Using List Comprehension
Let’s take another case, where you wish to only check if the string is a part of another word on the list and return all such words where your word is a sub-string of the list item.
Consider the list below:
ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi']
If you want to search for the substring Hello
in all elements of the list, we can use list comprehensions in the following format:
ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi'] matches = [match for match in ls if "Hello" in match] print[matches]
This is equivalent to the below code, which simply has two loops and checks for the condition.
ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi'] matches = [] for match in ls: if "Hello" in match: matches.append[match] print[matches]
In both cases, the output will be:
['Hello from AskPython', 'Hello', 'Hello boy!']
As you can observe, in the output, all the matches contain the string Hello
as a part of the string. Simple, isn’t it?
Using the ‘any[]’ method
In case you want to check for the existence of the input string in any item of the list, We can use the any[] method to check if this holds.
For example, if you wish to test whether ‘AskPython’ is a part of any of the items of the list, we can do the following:
ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi'] if any["AskPython" in word for word in ls]: print['\'AskPython\' is there inside the list!'] else: print['\'AskPython\' is not there inside the list']
Output
'AskPython' is there inside the list!
Using filter and lambdas
We can also use the filter[]
method on a
lambda function, which is a simple function that is only defined on that particular line. Think of lambda as a mini function, that cannot be reused after the call.
ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi'] # The second parameter is the input iterable # The filter[] applies the lambda to the iterable # and only returns all matches where the lambda evaluates # to true filter_object = filter[lambda a: 'AskPython' in a, ls] # Convert the filter object to list print[list[filter_object]]
Output
We do have what we expected! Only one string matched with our filter function, and that’s indeed what we get!
Conclusion
In this article, we learned about how we can find a string with an input list with different approaches. Hope this helped you with your problem!
References
- JournalDev article on finding a string in a List
- StackOverflow question on finding a string inside a List
How do I search for items that contain the string 'abc'
in the following list?
xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
The following checks if 'abc'
is in the list, but does not detect 'abc-123'
and 'abc-456'
:
if 'abc' in xs:
asked Jan 30, 2011 at 13:29
3
To check for the presence of 'abc'
in any string in the list:
xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
if any["abc" in s for s in xs]:
...
To get all the items containing 'abc'
:
matching = [s for s in xs if "abc" in s]
Mateen Ulhaq
22.2k16 gold badges86 silver badges127 bronze badges
answered Jan 30, 2011 at 13:32
Sven MarnachSven Marnach
543k114 gold badges914 silver badges816 bronze badges
19
Just throwing this out there: if you happen to need to match against more than one string, for example abc
and def
, you can combine two comprehensions as follows:
matchers = ['abc','def']
matching = [s for s in my_list if any[xs in s for xs in matchers]]
Output:
['abc-123', 'def-456', 'abc-456']
answered Aug 3, 2014 at 6:00
fantabolousfantabolous
19.7k6 gold badges52 silver badges47 bronze badges
3
Use filter
to get all the elements that have 'abc'
:
>>> xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
>>> list[filter[lambda x: 'abc' in x, xs]]
['abc-123', 'abc-456']
One can also use a list comprehension:
>>> [x for x in xs if 'abc' in x]
Mateen Ulhaq
22.2k16 gold badges86 silver badges127 bronze badges
answered Jan 30, 2011 at 13:34
MAKMAK
25.5k10 gold badges53 silver badges85 bronze badges
If you just need to know if 'abc' is in one of the items, this is the shortest way:
if 'abc' in str[my_list]:
Note: this assumes 'abc' is an alphanumeric text. Do not use it if 'abc' could be just a special character [i.e. []', ].
answered Apr 13, 2016 at 8:19
RogerSRogerS
1,1858 silver badges11 bronze badges
12
This is quite an old question, but I offer this answer because the previous answers do not cope with items in the list that are not strings [or some kind of iterable object]. Such items would cause the entire list comprehension to fail with an exception.
To gracefully deal with such items in the list by skipping the non-iterable items, use the following:
[el for el in lst if isinstance[el, collections.Iterable] and [st in el]]
then, with such a list:
lst = [None, 'abc-123', 'def-456', 'ghi-789', 'abc-456', 123]
st = 'abc'
you will still get the matching items [['abc-123', 'abc-456']
]
The test for iterable may not be the best. Got it from here: In Python, how do I determine if an object is iterable?
answered Oct 20, 2011 at 13:24
Robert MuilRobert Muil
2,8601 gold badge23 silver badges30 bronze badges
4
x = 'aaa'
L = ['aaa-12', 'bbbaaa', 'cccaa']
res = [y for y in L if x in y]
jamylak
123k29 gold badges227 silver badges227 bronze badges
answered Jan 30, 2011 at 13:31
MariyMariy
5,4883 gold badges39 silver badges57 bronze badges
0
for item in my_list:
if item.find["abc"] != -1:
print item
jamylak
123k29 gold badges227 silver badges227 bronze badges
answered Jan 30, 2011 at 13:38
RubyconRubycon
17.9k10 gold badges45 silver badges68 bronze badges
1
any['abc' in item for item in mylist]
answered Jan 30, 2011 at 13:34
ImranImran
83.5k23 gold badges96 silver badges128 bronze badges
I am new to Python. I got the code below working and made it easy to understand:
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
for item in my_list:
if 'abc' in item:
print[item]
answered Apr 7, 2018 at 7:52
Amol ManthalkarAmol Manthalkar
1,7221 gold badge15 silver badges16 bronze badges
0
Use the __contains__[]
method of Pythons string class.:
a = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
for i in a:
if i.__contains__["abc"] :
print[i, " is containing"]
kalehmann
4,5436 gold badges24 silver badges35 bronze badges
answered Feb 8, 2019 at 16:37
Harsh LodhiHarsh Lodhi
1394 silver badges10 bronze badges
If you want to get list of data for multiple substrings
you can change it this way
some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
# select element where "abc" or "ghi" is included
find_1 = "abc"
find_2 = "ghi"
result = [element for element in some_list if find_1 in element or find_2 in element]
# Output ['abc-123', 'ghi-789', 'abc-456']
answered Jul 14, 2020 at 2:43
I needed the list indices that correspond to a match as follows:
lst=['abc-123', 'def-456', 'ghi-789', 'abc-456']
[n for n, x in enumerate[lst] if 'abc' in x]
output
[0, 3]
answered Jan 5, 2020 at 19:02
Grant ShannonGrant Shannon
4,1521 gold badge40 silver badges33 bronze badges
mylist=['abc','def','ghi','abc']
pattern=re.compile[r'abc']
pattern.findall[mylist]
Bugs
4,4649 gold badges32 silver badges40 bronze badges
answered Jul 4, 2018 at 13:32
3
Adding nan to list, and the below works for me:
some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456',np.nan]
any[[i for i in [x for x in some_list if str[x] != 'nan'] if "abc" in i]]
answered Feb 18, 2021 at 2:38
Sam SSam S
4856 silver badges20 bronze badges
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
for item in my_list:
if [item.find['abc']] != -1:
print ['Found at ', item]
answered Mar 16, 2018 at 9:14
I did a search, which requires you to input a certain value, then it will look for a value from the list which contains your input:
my_list = ['abc-123',
'def-456',
'ghi-789',
'abc-456'
]
imp = raw_input['Search item: ']
for items in my_list:
val = items
if any[imp in val for items in my_list]:
print[items]
Try searching for 'abc'.
answered Jan 26, 2019 at 2:44
def find_dog[new_ls]:
splt = new_ls.split[]
if 'dog' in splt:
print["True"]
else:
print['False']
find_dog["Is there a dog here?"]
4b0
20.8k30 gold badges92 silver badges137 bronze badges
answered Jul 18, 2019 at 8:22
Question : Give the informations of abc
a = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
aa = [ string for string in a if "abc" in string]
print[aa]
Output => ['abc-123', 'abc-456']
answered Jun 16, 2018 at 10:52