0

I have a list that looks something like this:

['CALSIM', '1693', '1938', '1429', '1646', '1199', '1204', '1477', '1268', '1158', '1051', '998', '1135', '2381', '2513', 'Sky19', '1627', '2124', '1859', '2504', '1690', '1784', 'Sky21', 'Sky38', '2833', 'Sky20']

I want to create a new list from this list that only includes objects with the substring Sky in them. Is there a convenient way to do this?

Dila
  • 649
  • 1
  • 10

1 Answers1

0

You can use a conditional list composition to create a new list:

original_list = ['CALSIM', '1693', '1938', '1429', '1646', '1199', '1204', '1477', '1268', '1158', '1051', '998', '1135', '2381', '2513', 'Sky19', '1627', '2124', '1859', '2504', '1690', '1784', 'Sky21', 'Sky38', '2833', 'Sky20']

output_list = [x for x in original_list if 'sky' in x.lower()]

>>> output_list
['Sky19', 'Sky21', 'Sky38', 'Sky20']

The list comp checks each value of the list, converts it to lowercase (do you care about Sky vs sky vs SKY?), and checks if the string sky is in that value. If yes, it's added to output_list.

Because we're running various string operations on the values of original_list, this code will error if any of your values aren't strings. You could add extra checks to catch those if that's a possibility.

Danielle M.
  • 3,607
  • 1
  • 14
  • 31