Range of indexes in Python

Positive index  

We can specify element in list by the range of indexes in Python which start from the position and end with the position you want to index. It will return the value as list with the specific item.

For example 1:

myCar=['Toyota', 'Mitsubishi','Volvo','Honda','BMW']
print(myCar[1:3])
#output: ['Mitsubishi', 'Volvo']

 This is mean that index ‘ 1’ is ‘Mitsubishi’ and ‘ 3’ is for ‘Volvo’. So the output will only ‘Mitsubishi’ and ‘Volvo’.

For example 2:

This example shows about indexing item in list without first value, but it will collect all items from the first item in list to the value position that we assigned. The output start

myCar=['Toyota', 'Mitsubishi','Volvo','Honda','BMW']
print(myCar[:3])
#output: ['Toyota','Mitsubishi', 'Volvo'] 

For example:

This indexing item in list by leaving the second value,  it will collect all items from the position of the first value to end of list.

myCar=['Toyota', 'Mitsubishi','Volvo','Honda','BMW']
print(myCar[3:])
#output: ['Honda','BMW']

Negative index

We can navigate index by negative value. In this time, negative value will be indexed item from the end of list with the negative value.

 For example:

myCar=['Toyota', 'Mitsubishi','Volvo','Honda','BMW']
print(myCar[-3:-1])
#output: ['Volvo','Honda']

Index (-1) is  ‘Honda’ , Index(-3) is ‘Volvo’.  In case you want to collect ‘BMW’ & ‘Volvo’, you should use mycar[-3:], the output will be: [‘Volvo’,’BMW’].

freecode4learn.com

Leave a Reply