Subscriptions in the list

Created a list of flowers

 >>> flowers = ['rose','bougainvillea','yucca','marigold','daylilly','lilly of the valley'] 

Then

I had to assign a list of thorny subscriptions to the flowers list, consisting of the first three objects on 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 only the first 3 objects from the color list, while preserving the appearance of the list inside the list?

+7
source share
5 answers

Cutting notation [:3] not [0-3] :

 In [1]: flowers = ['rose','bougainvillea','yucca','marigold','daylilly','lilly of the valley'] In [2]: thorny=flowers[:3] In [3]: thorny Out[3]: ['rose', 'bougainvillea', 'yucca'] 
+13
source

In Python:

 thorny = flowers[1-3] 

This corresponds to flowers[-2] , because (1 - 3 == -2), and this means that it looks from the end of the list, that is, the second element from the end - for example, daylilly ...

To cut to (but not including) the first 3 elements, you can use thorny = flowers[:3] , and if you want everything after them, then it is flowers[3:] .

Read Python snippet

+6
source

You need to make flowers[0:3] (or, equivalently, flowers[:3] ). If you made flowers[0-3] (for example), this would be equivalent to flowers[-3] (ie, From the third to last element in flowers .).

+2
source

Here you go:

 thorny = flowers[0:3] 
+1
source

For any list there can be 3 possible types of subscriptions:

 e1 e2 e3 e4 e5 e6 e7 e8 e9 e10 << list elements |<--FirstFew-->| |<--LastFew-->| |<--MiddleElements-->| 
  • FirstFew is mainly represented by + ve indices.

     First 5 elements - [:5] //Start index left out as the range excludes nothing. First 5 elements, exclude First 2 elements - [2:5] 
  • LastFew is mainly represented 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] 
  • Middle elements can be represented by either a positive or a negative index.

     Above examples [2:5] and [-5:-2] covers this category. 

only the first 3 objects of the list flowers

 [0 : 3] //zero as there is nothing to exclude. or [:3] 
0
source

All Articles