Python Data Structures Tutorial - Python Tutorial | Logic Practice
Python Course / Other / Python Data Structures Tutorial

Python Data Structures Tutorial

BLUF: This lesson on Python Data Structures Tutorial provides a comprehensive guide to understanding and implementing this concept in Python. Whether you're a beginner or looking to refresh your knowledge, you'll find clear explanations and interactive code examples here.
Key Concept: Python Data Structures Tutorial

Mastering Python Data Structures Tutorial is essential for building efficient Python applications. Focus on the syntax and the best practices highlighted in this tutorial.

In Python, data structures serve as the foundational elements for organizing, managing, retrieving, and storing data, enabling more efficient access. Python is a high-level, object-oriented programming language that facilitates users in grasping the core principles of data structures and their associated algorithms with greater ease.

Data Structures in Python

Python offers various data structures, such as:

  • List
  • Tuple
  • Dictionary

Let's examine these data structures through illustrative examples:

Lists

Python Lists serve the purpose of holding various items of distinct data types within a single variable. They function similarly to arrays; however, there is one key distinction: unlike arrays, the elements in lists do not have to be of a uniform data type.

Lists are mutable, meaning they can be altered, removed, or substituted, and they are capable of holding duplicate elements. The functionality of a list is analogous to that of an array in C, vectors in C++, or ArrayList in Java.

Python List Example

Let's examine a straightforward illustration demonstrating the process of generating a list:

Example

Example

# creating list

list_1 = ['Example', 12, False, 1.6, 3e12]

print("List 1:", list_1)

# creating a nested list

list_2 = [['Example', 'Tech'], 3, True, 'Hello', 1.69]

print("List 2:", list_2)

Output:

Output

List 1: ['Example', 12, False, 1.6, 3000000000000.0]

List 2: [['Example', 'Tech'], 3, True, 'Hello', 1.69]

Explanation:

In the example provided, a basic list has been constructed utilizing square brackets ''. This list is composed of various elements that represent different data types. In the same manner, we have also formed a nested list, which is essentially a list contained within another list.

Tuple

A Python Tuple is characterized as a collection of objects. It operates similarly to a list, with the primary distinction being that Tuples are immutable. This immutability implies that once a tuple is created in Python, it is not possible to add, remove, or alter any of its elements. Like Lists, Tuples can also hold elements of diverse types.

In Python, tuples can be formed by arranging a series of values separated by commas, which may or may not be enclosed in parentheses to group the sequence of data.

Python Tuple Example

Here is a simple example to create a tuple.

Example

Example

# creating tuple

tuple_1 = ('Example', 19, True, 1.6, 5e3)

print("Tuple 1:", tuple_1)

# creating a nested tuple

tuple_2 = (('Hello', 'World'), 13, False, 'Example', 6.9)

print("Tuple 2:", tuple_2)

Output:

Output

Tuple 1: ('Example', 19, True, 1.6, 5000.0)

Tuple 2: (('Hello', 'World'), 13, False, 'Example', 6.9)

Explanation:

In the preceding illustration, we have formed a basic tuple by utilizing parentheses ''. This tuple is composed of various elements, each representing different data types. In a similar manner, we have also constructed a nested tuple, which refers to a tuple contained within another tuple.

A Python Set is an unordered collection designed to hold numerous elements within a single variable. Sets are also mutable, indicating that after a set is created in Python, you are unable to alter or modify the items it contains.

In Python, sets do not permit duplicate values; consequently, it is impossible to have two elements with identical values, which aids in the removal of repeated entries. Sets are frequently utilized for the purpose of membership testing. The implementation of sets relies on the widely-used Hashing method, which allows for operations such as insertion, deletion, and traversal to be performed in O(1) time on average.

Python Set Example

Let's examine a straightforward example that demonstrates the process of creating a set.

Example

Example

# creating set

set_1 = {'hello', 'logicpractice', 40, 21, 'hello', 19.2, False}

print("Set 1:", set_1)

# creating a set with a tuple an element

set_2 = {('logicpractice', 'tech'), 10, 10, 'welcome', 13.6, True}

print("Set 2:", set_2)

Output:

Output

Set 1: {False, 19.2, 'logicpractice', 21, 'hello', 40}

Set 2: {True, ('logicpractice', 'tech'), 'welcome', 10, 13.6}

Explanation:

In the preceding example, a set was formed by placing certain items within curly braces '{}'. It is evident that any duplicate items have been removed from this set. Additionally, it is important to note that the elements within a set are unordered. We have also constructed another set that includes a tuple, which is a sequence that cannot be altered.

Dictionary

A Python Dictionary serves the purpose of holding data in key: value pairs. Unlike lists, dictionaries are both ordered and mutable, and they do not permit duplicate keys. The values assigned to these keys can be of any data type, and they may include duplicates; however, the keys themselves are immutable and must remain unique, meaning no two keys can have the same value.

In a Dictionary, the indexing process relies on keys. They utilize the principle of hashing internally and can be of any hashable type, which refers to objects that are immutable, such as strings, numbers, tuples, and so forth.

Python Dictionary Example

Let’s examine a straightforward illustration of how to construct a dictionary.

Example

Example

# creating dictionary

dict_1 = {

    'name': 'Johnson',

    'age' : 19,

    'profession' : 'Software Developer',

    'company' : 'Example',

    'age' : 24

          }

print("Dictionary 1:", dict_1)

# creating a nested dictionary

dict_2 = {

    'name': 'Sachin',

    'dob' : {

        'date': 11,

        'month': 'March',

        'year': 1999

    },

    'profession' : 'Web Developer',

    'company' : 'Example'

    }

print("Dictionary 2:", dict_2)

Output:

Output

Dictionary 1: {'name': 'Johnson', 'age': 24, 'profession': 'Software Developer', 'company': 'Example'}

Dictionary 2: {'name': 'Sachin', 'dob': {'date': 11, 'month': 'March', 'year': 1999}, 'profession': 'Web Developer', 'company': 'Example'}

Explanation:

In the preceding example, a dictionary has been constructed by placing several 'key: value' pairs within curly braces '{}'. Notably, the key 'age' occurs more than once; as a result, the value associated with the first occurrence of this key is replaced by the value from the second occurrence, since dictionaries can only hold unique keys. Additionally, we have formed a nested dictionary, which is a dictionary that is used as a value within another dictionary.

String

In Python, strings are sequences of bytes that represent Unicode characters. For instance, the string "logicpractice" is composed of the following characters in order: 'l', 'o', 'g', 'i', 'c', 'p', 'r', 'a', 'c', 't', 'i', 'c', 'e'.

Python String Example

Let's understand this using an Example.

Example

Example

# creating a string

my_str = "Example"

print("My String:", my_str)

print()

# performing operations on string

# given string

given_str = "Welcome to our tutorial"

print("Given String:", given_str)

# printing results

print("Length of String:", len(given_str))

print("First Element of String:", given_str[0])

print("Last Element of String:", given_str[-1])

print("Fourth Element of String:", given_str[3])

Output:

Output

My String: C# Tutorial

Given String: Welcome to our tutorial

Length of String: 22

First Element of String: W

Last Element of String: h

Fourth Element of String: c

Explanation:

In this instance, we have generated a string by placing a text within double quotation marks ("…"). Additionally, we have executed several operations on the string, including determining its length and displaying the various components of the string.

Collections Module

The Python Collection Module serves as a container that offers a variety of built-in data types. Let us explore each of them individually.

S. No. Data Structures Description
1 Counters ThePython counteris a sub-class of the dictionary. It is used to keep the count of the elements in an iterable in the form of an unordered dictionary where the key represents the element in the iterable and value represents the count of that element in the iterable.
2 OrderedDict Python OrderedDictis like a dictionary, with the only difference being that it to maintain the insertion order of keys in a dictionary.
3 Deque Python Dequestands for Doubly Ended Queue. It is a list-like container used for accessing fast append and pop operations from both sides of the container. It supports both FIFO (First In, First Out) and LIFO (Last In, First Out) operations.
4 ChainMap Python ChainMap encapsulates different dictionaries into a single variable. It finds the key by searching all the dictionaries one by one unless the required value is found.
5 UserDict Python UserDict wraps all the dictionary objects. It acts as a container used by Python developer when they want to create their dictionary with some modified or new functionality.

Conclusion

In this instructional guide, we delved into the essentials of data structures within Python that facilitate data organization and manipulation. We examined built-in structures such as Lists, Tuples, Dictionaries, Sets, and Strings, as well as more specialized entities like the Collections Module. Each of these structures serves a distinct function in the realm of programming.

Grasping these data structures is highly beneficial as it enhances both the efficiency and readability of your code. Utilizing data structures also bolsters your ability to tackle problems effectively in Python.

Python Data Structures FAQs

1. What are the basic data structures in Python?

The following are the built-in data structures in Python:

  • List
  • Tuple
  • Dictionary
  • 2. What is the difference between a list and a tuple?

  • List is a mutable (changeable) data structure, while Tuple is immutable (cannot be changed).
  • List utilizes more memory and is slightly slower than tuple.
  • 3. When should we use a set in Python?

We can use a set when:

  • We need unique items.
  • We want fast membership tests.
  • We do not need order.
  • 4. Can a dictionary have duplicate keys?

No. Keys within a dictionary must remain unique. If duplicate keys are utilized, the most recently assigned value will replace the previous value associated with that key.

5. Which data structure is best for fast lookups?

Both Sets and Dictionaries provide an average time complexity of O(1) for retrieval operations.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience