Sitemap
Priyamaurya

Priyamaurya

6 min read7 hours ago

--

Understanding Python’s Built-in Data Structures: Lists, Tuples, Dictionaries, and Sets

Introduction

Python provides several built-in data structures that make handling data much easier. Among them, Lists, Tuples, Dictionaries, and Sets are some of the most commonly used.

At first, they might look quite similar because all of them can store multiple values. However, each one has its own purpose and behavior.

Press enter or click to view image in full size
Photo by Tai Bui on Unsplash

List

A list is an ordered and mutable collection of elements in Python. It allows us to store multiple values in a single variable.
One of the best things about lists is that they can contain different types of data, such as integers, strings, floats, and even other lists.

Lists are created using square brackets ‘[]’.

Example:

fruits = ["apple", "banana", "mango", "orange"]
print(fruits)

Output:

['apple', 'banana', 'mango', 'orange']

Important Features of List

1. Ordered
Lists maintain the order in which elements are inserted. Each element has an index, starting from 0.

fruits = ["apple", "banana", "mango"]
print(fruits[0])
print(fruits[2])

Output:

apple
mango

2. Mutable
Lists are mutable, which means we can modify their elements after creating them.

fruits = ["apple", "banana", "mango"]
fruits[1] = "grapes"
print(fruits)

Output:

['apple', 'grapes', 'mango']

3. Allows Duplicate Values
A list can contain duplicate elements.

numbers = [10, 20, 10, 30, 20]
print(numbers)

Output:

[10, 20, 10, 30, 20]

4. Allows Different Data Types

my_list = [10, "Python", 3.5, True]
print(my_list)

Common List Methods
Python provides several built-in methods to work with lists

append() — Adds an element at the end
insert() — Adds an element at a specific position
remove() — Removes a particular element
pop() — Removes an element by index (last element by default)
sort() — Sorts the list
reverse() — Reverses the list
clear() — Removes all elements

Example:

numbers = [10, 20, 30]
numbers.append(40)
numbers.insert(1, 15)
numbers.remove(30)
print(numbers)

Output:

[10, 15, 20, 40]

When should we use lists?
Lists are useful when we need to store multiple values and expect to add, remove, or update elements frequently. For example, storing student names, shopping items, or marks.

Tuple

A tuple is an ordered and immutable collection of elements. Just like lists, tuples can store multiple values of different data types.
The main difference is that tuples cannot be modified after they are created.

Tuples are created using parentheses ‘()’.

Example:

student = ("Priya", 22, "Computer Science")
print(student)

Output:

('Priya', 22, 'Computer Science')

Important Features of Tuples

1. Ordered
Tuples maintain the order of elements, and we can access them using indexing.

student = ("Priya", 22, "Computer Science")
print(student[0])
print(student[1])

Output:

Priya
22

2. Immutable
Once a tuple is created, its elements cannot be changed, added, or removed.

numbers = (10, 20, 30)
# This will raise a TypeError
numbers[1] = 50

3. Allows Duplicate Values

numbers = (10, 20, 10, 30)
print(numbers)

Output:

(10, 20, 10, 30)

4. Allows Different Data Types

my_tuple = (10, "Python", 5.5, True)
print(my_tuple)

Important Tuple Methods
Since tuples are immutable, they have fewer built-in methods than lists.

count() — Returns how many times an element appears
index() — Returns the index of an element

Example:

numbers = (10, 20, 30, 20, 40)
print(numbers.count(20))
print(numbers.index(30))

Output:

2
2

A small tip: If you want to create a tuple containing only one element, you must include a comma.
a = (10,)
Without the comma, Python treats it as an integer inside parentheses rather than a tuple.

When should we use tuples?
Tuples are useful when we have data that should remain unchanged. For example, storing coordinates, dates, or fixed configuration values.

Dictionary

A dictionary is a collection of data stored in the form of key-value pairs. Instead of accessing elements using their index, we access them using their keys.
Dictionaries are created using curly brackets ‘{}’ with each key and value separated by a colon ‘:’.

Get Priyamaurya’s stories in your inbox

Join Medium for free to get updates from this writer.

Example:

student = {
"name": "Priya",
"age": 22,
"course": "Python",
"marks": 85
}
print(student)

Output:

{'name': 'Priya', 'age': 22, 'course': 'Python', 'marks': 85}

Here, “name” is a key and “Priya” is its value.

Important Features of Dictionaries

1. Stored as Key-Value Pairs
Every dictionary element consists of a key and its corresponding value.

student = {"name": "Priya", "age": 22}
print(student["name"])

Output:

Priya

2. Mutable
We can add, update, and remove elements from a dictionary.

student = {"name": "Priya", "age": 22}
# Updating a value
student["age"] = 23
# Adding a new key-value pair
student["city"] = "Varanasi"
print(student)

Output:

{'name': 'Priya', 'age': 23, 'city': 'Varanasi'}

3. Keys Must Be Unique
A dictionary cannot have duplicate keys. If we use the same key more than once, the latest value will overwrite the previous one.

student = {
"name": "Priya",
"age": 22,
"name": "Shikha"
}
print(student)

Output:

{'name': 'Shikha', 'age': 22}

4. Values Can Be Duplicated
Different keys can have the same value.

marks = {
"Maths": 90,
"Physics": 90,
"Chemistry": 85
}

Common Dictionary Methods

keys() — Returns all keys
values() — Returns all values
items() — Returns key-value pairs
get() — Returns the value of a key
update() — Updates the dictionary
pop() — Removes a specified key
clear() — Removes all elements

Example:

student = {
"name": "Priya",
"age": 22,
"course": "Python"
}
print(student.keys())
print(student.values())
print(student.get("name"))

Output:

dict_keys(['name', 'age', 'course'])
dict_values(['Priya', 22, 'Python'])
Priya

When should we use dictionaries?
Dictionaries are useful when we need to store related information and retrieve it using meaningful keys. For example, student records, employee details, product information, and user profiles.

Set

A set is an unordered collection of unique elements. The most important thing about sets is that they do not allow duplicate values.
Sets are created using curly brackets ‘{}’.

Example:

numbers = {10, 20, 30, 40, 20, 10}
print(numbers)

Output (order may vary):

{10, 20, 30, 40}

Notice that duplicate values are automatically removed.

Important Features of Sets

1. Does Not Allow Duplicates
Every element in a set must be unique.

numbers = {1, 2, 2, 3, 3, 4}
print(numbers)

Output:

{1, 2, 3, 4}

2. Unordered
Sets do not maintain a guaranteed insertion order. Therefore, we cannot access elements using indexing.

numbers = {10, 20, 30}
# This will raise a TypeError
print(numbers[0])

3. Mutable
We can add or remove elements from a set after creating it.

numbers = {10, 20, 30}
numbers.add(40)
numbers.remove(20)
print(numbers)

Output (order may vary):

{10, 30, 40}

4. Supports Mathematical Operations
This is one of the most useful features of sets. Python allows us to perform operations like union, intersection, and difference.

Let’s understand them with an example.

A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

Union: Returns all unique elements from both sets.

print(A | B)

Output:

{1, 2, 3, 4, 5, 6}

Intersection: Returns only the common elements.

print(A & B)

Output:

{3, 4}

Difference: Returns elements present in the first set but not in the second.

print(A - B)

Output:

{1, 2}

Common Set Methods

add() — Adds an element
update() — Adds multiple elements
remove() — Removes an element (raises an error if missing)
discard() — Removes an element without an error if missing
union() — Combines two sets
intersection() — Returns common elements
difference() — Returns elements present only in the first set
clear() — Removes all elements

Note: An empty set is created using ‘set()’, because ‘{}’ creates an empty dictionary.

When should we use sets?
Sets are useful when we want to remove duplicate values, find common elements between collections, or perform mathematical set operations.
For example, finding unique email addresses or identifying common students between two classes.

Conclusion

Lists, Tuples, Dictionaries, and Sets are four important data structures in Python. Although they all help us store multiple values, each has a different purpose.

- Use Lists when you need an ordered collection that can be modified.
- Use Tuples when you want to store data that should remain unchanged.
- Use Dictionaries when you want to store information in key-value pairs.
- Use Sets when you need unique elements and want to perform set operations.

The best way to get comfortable with them is to practise different examples and solve small problems using each one.

Keep practising, keep experimenting, and happy coding!

--

--