1

I want to check if strings in a list of strings contain a certain substring. If they do I want to save that list item to a new list:

list = ["Maurice is smart","Maurice is dumb","pie","carrots"]

I have tried using the following code:

new_list = [s for s in list if 'Maurice' in list]

but this just replicates the list if one of its items is 'Maurice'. So I was wondering if, maybe, there was a way to solve this by using the following syntax:

if "Maurice" in list:
    # Code that saves all list items containing the substring "Maurice" to a new list

Result should then be:

new_list = ["Maurice is smart", "Maurice is dumb"]

If been looking for a way to do this but I can not find anything.

Mark Skelton
  • 3,663
  • 4
  • 27
  • 47

3 Answers3

5

You could do this:

list = ["Maurice is smart","Maurice is dumb","pie","carrots"]

new_list = [x for x in list if "Maurice" in x]

print(new_list)

Output:

['Maurice is smart', 'Maurice is dumb']
Mark Skelton
  • 3,663
  • 4
  • 27
  • 47
  • For anyone reading this answer: I recommend strongly not to use python built in names for your own variables. Using list as variable name here will prevent users of your code from using the keyword list. This can have all sorts of bad consequences. – DevShark Mar 22 '16 at 09:39
3

You can use a list comprehension.

Also, make sure not to use the built in list as variable name.

my_list = ["Maurice is smart", "Maurice is dumb", "pie", "carrots"]
[e for e in my_list if 'Maurice' in e]
DevShark
  • 8,558
  • 9
  • 32
  • 56
3

You could use Python's builtin filter:

data = ["Maurice is smart", "Maurice is dumb", "pie", "carrots"]
res = filter(lambda s: 'Maurice' in s, data)
print(res)

Output:

['Maurice is smart', 'Maurice is dumb']

The first argument is a predicate function (a simple lambda here) which must evaluate to True for the element of the iterable to be considered as a match.

filter is useful whenever an iterable must be filtered based on a predicate.

Also, a little extra, imagine now this data to be filtered:

data = ["Maurice is smart","Maurice is dumb","pie","carrots", "maurice in bikini"]
res = filter(lambda s: 'maurice' in s.lower(), list)
print(res)

Ouput:

['Maurice is smart', 'Maurice is dumb', 'maurice in bikini']
DevLounge
  • 8,313
  • 3
  • 31
  • 44
  • Exactly why should filter be always preferable to list comprehensions? http://stackoverflow.com/a/1247490/2243104 – Reti43 Mar 21 '16 at 22:05