Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sublist in a List

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?

like image 913
Robert Montz Avatar asked Nov 02 '12 00:11

Robert Montz


2 Answers

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-->|
  1. 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]
    
  2. 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]
    
  3. 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]
like image 67
Saurav Sahu Avatar answered Nov 15 '22 18:11

Saurav Sahu


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.).

like image 41
arshajii Avatar answered Nov 15 '22 16:11

arshajii