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)
Asked
Active
Viewed 75 times
-4

James Z
- 12,209
- 10
- 24
- 44
5 Answers
3
Split it on -
and then take the first split
for plant in data:
plant_name, category = plant.split(' -', 1)
if "Flower" in category:
flowers.append(plant_name)
else:
shrubs.append(plant_name)

Sayse
- 42,633
- 14
- 77
- 146
0
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.

Maxisy
- 50
- 1
- 6
0
print([flower[:flower.index(' - Flower')] for flower in flowers])
To omit the " - Flower" suffix from the strings when printing. List comprehension is very useful, I highly recommend you check it out eventually

Nicholas Hansen-Feruch
- 974
- 8
- 16
0
flowers = [x.split(' - ')[0] for x in data if x.split(' - ')[1] == 'Flower']
shrubs = [x.split(' - ')[0] for x in data if x.split(' - ')[1] == 'Shrub']
print(flowers)
print('--------')
print(shrubs)
Result:
['Bellflower', 'China Pink', 'Daffodil', 'Evening Primrose', 'French Marigold', 'Iris', "Queen Anne's Lace", 'Red Hot Poker', 'Snapdragon', 'Sunflower', 'Tiger Lily']
['Andromeda', 'Hydrangea', 'Japanese Camellia', 'Lavender', 'Lilac', 'Magnolia', 'Peony', 'Witch Hazel']

Barry the Platipus
- 9,594
- 2
- 6
- 30