Loading...

Go Back

Next page
Go Back Course Outline

Python Full Course


Data Structures in Python

Python Basics

Data Structures in Python

Python provides several built-in data structures that help you store and organize data efficiently. These include lists, tuples, sets, and dictionaries.

1. List

Ordered, changeable, and allows duplicate items.

fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
2. Tuple

Ordered, unchangeable (immutable), and allows duplicates.

colors = ("red", "green", "blue")
3. Set

Unordered, unchangeable (but you can add/remove items), and does not allow duplicates.

unique_numbers = {1, 2, 3, 4}
unique_numbers.add(5)
4. Dictionary

Unordered (as of Python 3.6+, now ordered), changeable, and stores data in key-value pairs.

person = {
  "name": "Alice",
  "age": 25,
  "city": "New York"
}
print(person["name"])
Quick Comparison:
Structure Ordered Mutable Use Case
List Yes Yes General-purpose data storage
Tuple Yes No Fixed data collections
Set No Yes Unique item storage
Dictionary Yes (3.7+) Yes Key-value mappings
Tip:

Choose the right data structure based on what you need—order, uniqueness, or fast access using keys.

Python Data Structures

Lists

Lists are ordered, mutable collections that can store multiple data types.


                                numbers = [1, 2, 3, 4, 5]
                        print(numbers)
[1, 2, 3, 4, 5]

Tuples

Tuples are ordered, immutable collections.


                                numbers = (1, 2, 3)
                        print(numbers)
(1, 2, 3)


Dictionaries

Dictionaries store key-value pairs.


                                person = {"name": "John", "age": 25}
                        print(person)
{'name': 'John', 'age': 25}

Sets

Sets store unique elements and support set operations.


                                A = {1, 2, 3, 4}
                        B = {3, 4, 5, 6}
                        print(A | B)
{1, 2, 3, 4, 5, 6}


Set Operations

Set operations allow mathematical operations such as union, intersection, and difference.


                                A = {1, 2, 3, 4}
                        B = {3, 4, 5, 6}
                        print(A & B)  # Intersection
                        print(A - B)  # Difference
                        print(A ^ B)  # Symmetric Difference
{3, 4} {1, 2} {1, 2, 5, 6}

Set Methods

Sets support various methods for modification.


                                numbers = {1, 2, 3}
                        numbers.add(4)
                        numbers.remove(2)
                        numbers.discard(5)
                        numbers.clear()
                        print(numbers)
set()
Go Back

Next page