Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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

1 Answer

0 votes
by (106k points)

We have several methods to get the items associated with abc some of the important is as follows:-

To get all the items containing abc you can use the list-comprehension below is the piece of code that illustrates how we do that:-

my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']

matching = [s for s in some_list if "abc" in s]

image

If you want to know more about the list-comprehension you can visit the following website:-

https://intellipaat.com/blog/tutorial/python-tutorial/python-lists/

Another thing you can use the filter method to get the items associated with abc:-

my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']

print filter(lambda x: 'abc' in x, my_list)

image

Related questions

0 votes
1 answer
asked Sep 26, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...