I have a list:
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
and want to search for items that contain the string 'abc'
. How can I do that?
if 'abc' in my_list:
would check if 'abc'
exists in the list but it is a part of 'abc-123'
and 'abc-456'
, 'abc'
does not exist on its own. So how can I get all items that contain 'abc'
?
Use
filter
to get at the elements that haveabc
.You can also use a list comprehension.
By the way, don't use the word
list
as a variable name since it is already used for thelist
type.From my knowledge, a 'for' statement will always consume time.
When the list length is growing up, the execution time will also grow.
I think that, searching a substring in a string with 'is' statement is a bit faster.
But, I agree that the
any
statement is more readable.This is the shortest way:
I'm new to python. Got below code working and easy to understand