'Getting elements from a list that has a prefix

Let's say I have a few lists:

list = ["MacOS-1", "MacOS-2", "Windows-1", "Windows-2"]
maclist = []
windowslist = []

How do I get elements from "list" and sort them into "maclist" or "windowslist" according to if they have "MacOS" or "Windows" in front of them?

I was thinking: (I haven't tested this yet)

for element in list:
  if "MacOs" in element:
    maclist.append(element)
  elif "Windows" in element:
    windowslist.append(element)

Thanks in advance...



Solution 1:[1]

You can use startswith function in Python.

for element in list:
  if element.startswith("MacOS"):
    maclist.append(element)
  elif element.startswith("Windows"):
    windowslist.append(element)

In your code, you don't only check prefixes, also you check all substrings in any index range.

Or, you can use the below implementation:

macos_list = [item for item in item_list if item.startswith("MacOS")]
windows_list = [item for item in item_list if item.startswith("Windows")]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gokhan_ozeloglu