A beginner's guide to understanding Data Structures
Lists, Tuples, Sets and Dictionaries
Lists
By definition, a List is a data type for mutable and ordered sequence of elements. Lists are placed within square brackets []
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:
max()
- returns the greatest value/object within the listlen()
- returns the number of objects in the listsorted()
- returns a copy of the list in ascending order while retaining the original listmin()
- returns the smallest value/objectsorted(), reverse = True
- returns a copy of the list in descending order
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()