Sunday, April 01, 2018

Accessing array items in Python is easy using indexing

Looks like a trick question.

There is no Array in Python but an object List exists which can be used to the same end.
  • The List may contain different list items or same kind of list items.
  • The List is indexed and zero based. The first list item has an index 0.
  • You can retrieve list items using their index. Even negative index is OK.
As defined here lst is a list .

lst=["a", "b", "c", "e"]

The list can have strings like this as well:

lst2=['a', 'b', 'c', 'e']

They both evaluate to the same: ['a', 'b', 'c', 'e']

List may contain different types of List Items as in this definition.

 lst2=["ab", 8, True, 5.8]

Retrieving list items using index
>>> lst[0]
>>> lst[-1]
>>> lst2[-2]
>>> lst[5]
Traceback (most recent call last):
  File "", line 1, in
IndexError: list index out of range

Negative Index
>>> lst[-1]
>>> lst2[-2]

These evaluations were carried out using Python 3.6.2

No comments: Protection Status