1

OK, in Python I have list:

flowers = ["rose", "bougainvillea", "yucca", "marigold", "daylilly", "lilley of the valley"]

Now, I want to assign just the last object of list flowers to a new list called poisonous.

I tried:

poisonous=flowers[-1]

However this statement makes poisonous a string instead of a list.

karthikr
  • 97,368
  • 26
  • 197
  • 188

4 Answers4

3
>>> poisonous=[flowers[-1],] #take the last element and put it in a list
>>> poisonous
['lilley of the valley']
>>> poisonous=flowers[-1] #take the last element, which is a string
>>> poisonous
'lilley of the valley'
>>> poisonous=flowers[-1:] #take a slice of the original list. The slice is also a list.
>>> poisonous
['lilley of the valley']
CT Zhu
  • 52,648
  • 17
  • 120
  • 133
2

Try this instead

poisonous=flowers[-1:]

Demo:

>>> flowers = ["rose", "bougainvillea", "yucca", "marigold", "daylilly", "lilley of the valley"]
>>> 
>>> flowers[-1:]
['lilley of the valley']

Your issue was, you were indexing, which returns an object. Whereas, slicing would return a list.

karthikr
  • 97,368
  • 26
  • 197
  • 188
1

You can wrap the object to be assigned in square bracket to make it a list assignment.

poisonous = [flowers[-1]]
edi_allen
  • 1,878
  • 1
  • 11
  • 8
0

And, probably more useful:

flowers = [
    "rose", 
    "bougainvillea", 
    "poison oak",
    "yucca", 
    "marigold", 
    "daylily", 
    "lily of the valley",
]

snakes = [
    "king",
    "rattler",
]

poisonous = []

poisonous.append(flowers[-1])
poisonous.append(snakes[-1])

print poisonous

--output:--
['lily of the valley', 'rattler']
7stud
  • 46,922
  • 14
  • 101
  • 127