data = [
"Andromeda - Shrub",
"Bellflower - Flower",
"China Pink - Flower",
"Daffodil - Flower",
"Evening Primrose - Flower",
"French Marigold - Flower",
"Hydrangea - Shrub",
"Iris - Flower",
"Japanese Camellia - Shrub",
"Lavender - Shrub",
"Lilac - Shrub",
"Magnolia - Shrub",
"Peony - Shrub",
"Queen Anne's Lace - Flower",
"Red Hot Poker - Flower",
"Snapdragon - Flower",
"Sunflower - Flower",
"Tiger Lily - Flower",
"Witch Hazel - Shrub",
]
flowers = []
shrubs = []
for plant in data:
if "- Flower" in plant:
flowers.append(plant)
else:
shrubs.append(plant)
print(flowers)
print(shrubs)
>Solution :
You could use:
for plant in data:
to_append = plant.split(" - ")[0]
if "- Flower" in plant:
flowers.append(to_append)
else:
shrubs.append(to_append)
This will split the plant using " – " and make an array, then save to the to_append variable the first index of that array.
So for example if you take "Andromeda - Shrub" this will create an array {"Andromeda", "Shrub"} and its 0 index will be "Andromeda", which you then add to the new array.