Skip to main content Accessibility help
Internet Explorer 11 is being discontinued by Microsoft in August 2021. If you have difficulties viewing the site on Internet Explorer 11 we recommend using a different browser such as Microsoft Edge, Google Chrome, Apple Safari or Mozilla Firefox.

Chapter 4: Python Data Structures

pp. 85-144

Authors

, Techno India Hoogly
  • Get access
  • Add bookmark
  • Export citation
  • Share

Extract

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:

myList = [ ]

An empty list can also be created using a constructor as:

myList = list( )

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 [ ].

About the book

Access options

Review the options below to login to check your access.

Purchase options

eTextbook
US$99.99
Paperback
US$99.99

Have an access code?

To redeem an access code, please log in with your personal login.

If you believe you should have access to this content, please contact your institutional librarian or consult our FAQ page for further information about accessing our content.

Also available to purchase from these educational ebook suppliers