Built-in Data Structures in Pyhton
- anitakhatri31
- May 2
- 5 min read
Data structures are fundamental constructs for organizing and storing data in a way that enables efficient access and modification. Python offers several built-in data structures, each suited for different purposes. These can be broadly categorized into mutable and immutable structures. These data structures offer different functionalities and are suitable for various use cases depending on the specific requirements of the program

Lists
Lists are a fundamental, versatile, and mutable data structure in Python used to store ordered collections of items. They are defined by enclosing a comma-separated sequence of elements within square brackets []. Lists can contain elements of different data types, including numbers, strings, and even other lists, enabling the creation of complex data structures.
Key Characteristics of Lists:
· Ordered: Elements in a list maintain their insertion order.
· Mutable: Lists can be modified after creation; elements can be added, removed, or changed.
· Dynamic: Lists can grow or shrink in size as needed.
· Iterable: Lists can be traversed using loops.
· Indexed: Elements can be accessed by their position (index), starting from 0.
· Allows Duplicates: Lists can contain multiple occurrences of the same value.
Example :
colors = ["Red", "Orange", "Yellow"]
print(colors[2])
Python list with different data types:
a = [1, 10.2, "ABC", 40, True]
print(a)
# Accessing elements using indexing
print(a[0]) # 1
print(a[1]) # 10.2
print(a[2]) # "ABC"
print(a[3]) # 40
print(a[4]) # True
# Checking types of elements
print(type(a[1])) # float
print(type(a[4])) # bool

Adding Elements into List
1. append(): Adds an element at the end of the list.
2. extend(): Adds multiple elements to the end of the list.
3. insert(): Adds an element at a specific position. It takes two arguments: the index where the element should be inserted, and the element itself.
Example of append:
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
my_list.append([5,6])
print(my_list) # Output: [1, 2, 3, 4, [5, 6]]

Example of extend():
my_list = [1, 2, 3]
my_list.extend([4, 5, 6])
print(my_list) # Output: [1, 2, 3, 4, 5, 6]
my_list.extend(("a", "b"))
print(my_list) # Output: [1, 2, 3, 4, 5, 6, 'a', 'b']

Example of insert():
my_list = [1, 2, 3]
my_list.insert(1, 4) # Insert 4 at index 1
print(my_list) # Output: [1, 4, 2, 3]

Updating elements in a list:
Access the element:
Use the index of the element you want to change within square brackets []. Python lists are zero-indexed, meaning the first element is at index 0, the second at index 1, and so on.
Assign the new value:
Use the assignment operator = to assign the new value to the accessed element.
my_list = [10, 20, 30, 40, 50]# Change the element at index 2 (which is 30) to 35
my_list[2] = 35print(my_list) # Output: [10, 20, 35, 40, 50]

You can also update a range of elements using slicing:
my_list = [10, 20, 30, 40, 50]# Change the elements from index 1 to 3 (exclusive)
my_list[1:3] = [22, 33]print(my_list) # Output: [10, 22, 33, 40, 50]

Removing elements in a list:
Three primary methods exist in Python for removing elements from a list: remove(), pop(), and the del statement. Each method serves a different purpose and operates in a unique way.
1. remove():
The remove() method searches for the first occurrence of a specified value within the list and removes it. If the value is not found, it raises a ValueError.
Example:
my_list = [1, 2, 3, 2, 4]
my_list.remove(2) # Removes the first occurrence of 2
print(my_list) # Output: [1, 3, 2, 4]
my_list.remove(5) # Raises ValueError because 5 is not in the list

2. pop():
The pop() method removes the element at a given index and returns it. If no index is specified, pop() removes and returns the last element in the list.
Eample:
my_list = ['a', 'b', 'c', 'd']
removed_element = my_list.pop(1) # Removes element at index 1 ('b')
print(my_list) # Output: ['a', 'c', 'd']
print(removed_element) # Output: b
last_element = my_list.pop() # Removes the last element ('d')
print(my_list) # Output: ['a', 'c']
print(last_element) #Output: d

3. del statement
The del statement removes the element at a specified index or a slice of elements. It can also be used to delete the entire list. It does not return the removed element.
Example:
my_list = [5, 6, 7, 8, 9]
del my_list[2] # Removes element at index 2 (7)
print(my_list) # Output: [5, 6, 8, 9]
del my_list[1:3] # Removes elements from index 1 to 2
print(my_list) # Output: [5, 9]
# del my_list # Deletes the entire list
# print(my_list) # Raises NameError because the list no longer exists

Tuples
Tuples are ordered, immutable collections of items in Python. They are similar to lists, but once a tuple is created, its elements cannot be changed, added, or removed. Tuples are defined using parentheses () and elements are separated by commas.
Like Lists, tuples are ordered and we can access their elements using their index values
We cannot update items to a tuple once it is created.
Tuples cannot be appended or extended.
We cannot remove items from a tuple once it is created.
Creating Tuples:
empty_tuple = ()
my_tuple = (1, "hello", 3.4)
print(my_tuple)

Accessing Elements:
Tuple elements can be accessed using indexing, starting from 0 for the first element.
my_tuple = (1, "hello", 3.4)print(my_tuple[0]) # Output: 1print(my_tuple[1]) # Output: hello
#Tuple using Negative Index
my_tuple = (10, 5, 20)
print("Value in t[-1] = ", my_tuple[-1])
print("Value in t[-2] = ", my_tuple[-2])
print("Value in t[-3] = ", my_tuple[-3])

# Tuples can be repeated using the * operator
my_tuple = ("hello",)
repeated_tuple = my_tuple * 3
print(repeated_tuple) # Output: ('hello', 'hello', 'hello')

Sets
Sets in Python are unordered collections of unique elements. They are mutable, meaning elements can be added or removed after creation, but each element within a set must be immutable (e.g., numbers, strings, tuples). Sets are defined using curly braces {} or the set() constructor.
No duplicates - Elements must be uniuqe.
Unordered
Mutatble - can add or remove elements
Optimized - Fast lookups
Creating Sets:
# Empty setempty_set = set()# Set with initial values
my_set = {1, 2, 3}
my_set_from_list = set([1, 2, 2, 3]) # Duplicates are automatically removed
print(empty_set)
print(my_set)
print(my_set_from_list)
# Output:
# set()
# {1, 2, 3}
# {1, 2, 3}

Adding elements in Sets:
my_set = {1, 2, 3}# Add element
my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}

Removing elements in Sets:
my_set = {1, 2, 3, 4}# Remove element
my_set.remove(4)
print(my_set) # Output: {1, 2, 3}

# Check for membership
print(1 in my_set) # Output: True
print(4 in my_set) # Output: False
# Set lengthprint(len(my_set)) # Output: 3

Set Operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
Union: Combines elements from two sets.
# Union
print(set1 | set2)
print(set1.union(set2)) # Output: {1, 2, 3, 4, 5}
Intersection: Returns elements common to both sets.
# Intersection
print(set1 & set2)
print(set1.intersection(set2)) # Output: {3}
Difference: Returns elements in the first set but not the second.
# Difference
print(set1 - set2)
print(set1.difference(set2)) # Output: {1, 2}
Symmetric Difference: Returns elements present in either set, but not in both.
# Symmetric difference
print(set1 ^ set2)
print(set1.symmetric_difference(set2)) # Output: {1, 2, 4, 5}
Subset and Superset: Checks if one set is contained within another.
# Subset and Superset
print({1, 2}.issubset(set1)) # Output: True
print(set1.issuperset({1, 2})) # Output: True

Dictionaries
Dictionaries are ordered mappings for storing objects of mixed datatypes.
Objects are stored in the form of key, value pairs and curly brackets {} are used to store the objects. Keys and Values are separated by a colon (:) and key-value pairs are separated by a comma.
Dictionaries are changeable, which means that more key value pairs can be added or removed after creating a dictionary.
Creating a dictionary
# Creating a dictionary
student = { "name": "Alice", "age": 20, "major": "Computer Science"}
Accessing values using keys
# Accessing values using keys
name = student["name"]
print(name) # Output: Alice

Modifying values
# Modifying values
student["age"] = 21
print(student["age"]) # Output: 21

Adding new key-value pairs
# Adding new key-value pairs
student["gpa"] = 3.8
print(student) # Output: {'name': 'Alice', 'age': 21, 'major': 'Computer Science', 'gpa': 3.8}

Removing key-value pairs
# Removing key-value pairs
del student["major"]
print(student) # Output: {'name': 'Alice', 'age': 21, 'gpa': 3.8}



