Created a list flowers
>>> flowers = ['rose','bougainvillea','yucca','marigold','daylilly','lilly of the valley']
Then,
I had to assign to list thorny
the sublist of list flowers
consisting of the first three objects in the list.
This is what I tried:
>>> thorny = []
>>> thorny = flowers[1-3]
>>> thorny
'daylilly'
>>> thorny = flowers[0-2]
>>> thorny
'daylilly'
>>> flowers[0,1,2]
Traceback (most recent call last):
File "<pyshell#76>", line 1, in <module>
flowers[0,1,2]
TypeError: list indices must be integers, not tuple
>>> thorny = [flowers[0] + ' ,' + flowers[1] + ' ,' + flowers[2]]
>>> thorny
['rose ,bougainvillea ,yucca']
How can I get just the first 3 objects of list flowers, while maintaining the look of a list inside a list?
There can be 3 possible sublist types for any given list:
e1 e2 e3 e4 e5 e6 e7 e8 e9 e10 << list elements
|<--FirstFew-->| |<--LastFew-->|
|<--MiddleElements-->|
FirstFew are mostly presented by +ve indexes.
First 5 elements - [:5] //Start index left out as the range excludes nothing.
First 5 elements, exclude First 2 elements - [2:5]
LastFew are mostly presented by -ve indexes.
Last 5 elements - [-5:] //End index left out as the range excludes nothing.
Last 5 elements, exclude Last 2 elements - [-5:-2]
MiddleElements can be presented by both positive and negative index.
Above examples [2:5] and [-5:-2] covers this category.
just the first 3 objects of list flowers
[0 : 3] //zero as there is nothing to exclude.
or
[:3]
You'll want to do flowers[0:3]
(or equivalently, flowers[:3]
). If you did flowers[0-3]
(for instance) it would be equivalent to flowers[-3]
(i.e. the third to last item in flowers
.).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With