Akhil Bhadwal | 15 Nov, 2022

Python Data Structures Explained in Detail


Every programming language has provision for data structures. In the Python programming language, there are a total of 4 inbuilt data structures. These are namely list, tuple, dictionary, and set. Each of them is unique in its own right.

Data structures are an indispensable part of programming. As such, all good books on Python programming detail out on data structures to some extent.

Python Data Structures

List

A data structure that stores an ordered collection of items in Python is called a list. In other words, a list holds a sequence of items. You need to put all the items, separated by commas, in square brackets to let Python know that a list has been specified. The general syntax of a list is:

some_list = [item 1, item 2, item 3,….., item n]

Any list can have any number of elements and of different data types. Moreover, a list can have another list as an element. Such a list is known as a nested list. For example,

some_nested_list = [item 1, some_list, item 3,….., item n]

After creating a list in Python, it is possible to search, add, and remove items from the list. A list qualifies for being labeled as a mutable data type because it can be altered by adding or removing elements.

A list in the Python programming language is an example of using objects and classes. For instance, assigning a value, say 22, to an integer variable, let it be i, is creating an object of the class integer. The list is, therefore, also a type of class in Python.

Any class can have methods, which can be used only when we have an object of that specific class. For example, the append () method allows adding an item to the end of a list. The general syntax for the method is:

some_list.append(‘some item’)

Here some_list is the name of the list and some item is the element to be added to the list. A class can have fields, which are variables defined to use with an instance of that class only. Following are the various methods supported by lists in Python:

  • append () – Adds an element to the end of the list
  • clear () – Removes all elements from the list
  • copy () – Returns a shallow copy of the list
  • count () – Returns the total number of items passed as an argument
  • extend () – Adds all elements of a list to some other list
  • index () – Returns the index of an element (Note: If the same element appears multiple times in the list then the index of the very first match is returned)
  • insert () – Inserts an element to the list at the defined index
  • pop () – Eliminates and returns an element from the list
  • remove () – Eliminates an element from the list
  • reverse () – Reverses the order of all elements of the list
  • sort () – Sort all elements of a list in the ascending order

Tuple

Similar to a list, the tuple is a built-in data structure in Python. However, it doesn’t support the same level of extensive functionality. The most important difference between a list and a tuple is mutability. Unlike lists, tuples are immutable i.e. they can’t be modified.

Typically, a tuple in the Python programming language is defined using parentheses with each item separated by commas. Though adding parentheses to the tuple is optional, its use is recommended to clearly define the end and start of the tuple. The general syntax of a tuple is:

some_tuple = (item 1, item 2, item 3,….., item n)

Tuples are used in scenarios where it is certain that the (set of) values belonging to some statement or a user-defined function will not change.

In order to define an empty tuple, an empty pair of parentheses is used. For example,

empty_tuple = ()

Defining a tuple with a single item is a bit tricky. You need to specify the same using a comma following the only item. This is done in order to allow Python to differentiate between a tuple and a pair of parentheses surrounding the object in some expression.

So, a tuple, say singleton_tuple, with a single item, say item 1, is defined as:

singleton_tuple = (item 1, )

Similar to string indices, tuple indices start at 0. Like strings, tuples can be concatenated and sliced. Methods available for tuples are:

  1. cmp () Compares elements of two tuples
  2. len () Gives out the total length of some tuple
  3. max () Returns the biggest value from a tuple
  4. min () Returns the smallest value from a tuple
  5. tuple () Converts some list into a tuple

Sequences

Lists and tuples qualify to be called as sequences, just like strings. The most distinguishing features of a sequence are membership tests and indexing operations. The latter allows directly fetching an item(s) from the sequence.

Python provides support for three types of sequences; lists, strings, and tuples. Each of them supports the slicing operation. It allows retrieving a particular portion of the sequence.

Recommend Python Course

Complete Python Bootcamp From Zero to Hero in Python

Dictionary

Another type of built-in data structure in Python is the dictionary. It stores data in the form of key-value pairs. The keys defined for a dictionary need to be unique. Though values in a dictionary can be mutable or immutable objects, only immutable objects are allowed for keys.

A dictionary in Python is defined using key-value pairs, separated by commas, enclosed within curly braces. The key and value are separated using a colon. The general syntax of a dictionary is:

some_dictionary =

The key-value pairs in a dictionary don’t follow any specific order. Hence, you need to sort them manually for maintaining some kind of order. Any dictionary defined in the Python programming language is an instance of the dict class.

In order to access any key-value pair, the key needs to be specified using the indexing operator. The del statement is used for deleting one or many key-value pairs from a dictionary. The in operator is there for checking whether a key-value pair exists in the dictionary or not.

The indexing operator is also used for adding a new key-value pair. Using keyword arguments in functions is much similar to using dictionaries.

Set

Simply, a set is an unordered collection of simple objects in Python. In addition to being iterable and mutable, a set has no duplicate elements. Any set defined in Python is an instance of the set class.

Compared to a list, a set is advantageous by virtue of having a highly optimized method for checking whether some element is contained in the set or not. The general syntax of a set is:

some_set = {“item 1”, “item 2”, “item 3”,….., “item n”}

Typically, a set is employed when the existence of an object in a collection is much more important than the order or the frequency (number of times it appears) of the same.

Using sets allow testing for membership, such as checking whether a set is a subset of some other set and finding the intersection between two sets. Sets in Python follow the mathematical concept of set theory.

There is something called frozen sets in Python. A frozen set is a set that supports only those methods and operators that produce a result without affecting the frozen set or set(s) to which the same are applied. Methods supported by sets are:

  • add () – Adds an item to the set (Note: As sets don’t have repeating values, the item that is to be added to a set must not be already a member of the set.)
  • clear () – Removes all items of the set
  • difference () – Returns a set with all elements of the invoking set but not of the second set
  • intersect () – Returns an intersection of two sets
  • union () – Returns a union of two sets

Summary

So, that sums up all about the Python data structures. Learning Python is incomplete without building a good understanding of data structures. I hope the article will help you better understand and utilize data structures in your Python projects.

Use the dedicated comments window below to share your opinions and views on data structures or the article with us. You can also ask all your queries via comments. We’ll try our best to help you out.

People are also Reading:

By Akhil Bhadwal

A Computer Science graduate interested in mixing up imagination and knowledge into enticing words. Been in the big bad world of content writing since 2014. In his free time, Akhil likes to play cards, do guitar jam, and write weird fiction.

View all post by the author

Subscribe to our Newsletter for Articles, News, & Jobs.

I accept the Terms and Conditions.

Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.

In this article

Learn More

Please login to leave comments

Vijay Singh Khatri

Can you tell us the points which you want in this blog?

5 years ago