In the previous chapter we have studied about arrays. An array is a widely used data structure in almost every high level programming languages. In this chapter we will discuss some very useful data structures of Python. These are lists, tuples, sets, and dictionaries. All these data structures are of type compound data structures since they consist of some basic or primitive data structure/data type.
4.1 Lists
List is a very important and useful data structure in Python. It has almost all the functionalities of an array but with more flexibility. Basically a list is a collection of heterogeneous elements. List items are ordered, which means elements of a list are stored in a specific index position. List items are mutable, which indicates that it is possible to change or edit the elements of a list, and duplicate items are allowed in a list. Another important feature of a list is that it is dynamic. It can grow or shrink during program execution according to our requirement.
4.1.1 Creating a List
A list is a collection of elements that are separated by commas (,) inside a pair of square brackets. Hence we can create a list by putting comma separated elements within square brackets. The general format to defining a list is:
List_variable = [ value1, value2, …. ]
Hence we may create a list of integers as:
myIntList = [10, 12, 25, 37, 49 ]
A list of string can be created as:
nameList = [“Amit”, “Sudip”, “Dibyendu”, “Sourav”]
A list with heterogeneous data can be created as:
myList = [ 25, “Sudip Chowdhury”, 87.2]
An empty list can be created as:
An empty list can also be created using a constructor as:
4.1.2 Accessing List Elements
List elements are accessed just like array elements, i.e., the elements of a list are accessed using a list index. Like arrays, in case of lists also the index value starts from 0. Hence, the first position of a list is 0, second is 1, and so on. To access a list element we need to mention the list name followed by the list index enclosed within [ ].