A beginner's guide to understanding Data Structures

Lists, Tuples, Sets and Dictionaries

A beginner's guide to understanding Data Structures

Lists

By definition, a List is a data type for mutable and ordered sequence of elements. Lists are placed within square brackets []

Lists - Kenyan towns.png

List Indexing

Lists are indexed using Python's zero based indexing rules. This implies how far an item/object is from the beginning e.g.,

months = ['January', 'February', 'March', 'April', 'May']

print (months[1])

>>> February

Additionally, lists can contain a mix and match of data types e.g int, float, string, bool

random_list = [1, 4.5, 'this is a string', True]

List Slicing

The most important thing to note here is that when slicing, the lower bound index is always inclusive and the upper bound index is exclusive. For example,

months = ['January', 'February', 'March', 'April', 'May']

print (months[1:3])

>>> ['February', 'March']

In the above example, February is index 1 (lower bound), whereas April is index 3 (upper bound). In this case, the upper bound is ignored and thus March is returned.

List Methods

Examples of List Methods include:

  1. max() - returns the greatest value/object within the list
  2. len() - returns the number of objects in the list
  3. sorted() - returns a copy of the list in ascending order while retaining the original list
  4. min() - returns the smallest value/object
  5. sorted(), reverse = True - returns a copy of the list in descending order

Lists Methods.png

NB: For strings max() returns the value with the highest order alphabetically as illustrated below:

second_list = ['Kaka Travellers', 'Bahima Shuttle', 'Tripple 8 Services', 'Sony Classic']

print (max(second_list))

>>> Tripple 8 Services

The inverse is true for min()