Friday, March 30, 2018

How do you define an Array in Python?

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]
'a'
>>> lst[-1]
'e'
>>> lst2[-2]
True
>>> lst[5]
Traceback (most recent call last):
  File "", line 1, in
IndexError: list index out of range

Negative Index
>>> lst[-1]
'e'
>>> lst2[-2]
True



These evaluations were carried out using Python 3.6.2


No comments: