Python Course
Python provides several built-in data structures that help you store and organize collections of data. Each structure has different properties like ordering, mutability, and uniqueness.
Common Data Structures:
Type Example Description list [1, 2, 3] Ordered, mutable tuple (1, 2, 3) Ordered, immutable set {1, 2, 3} Unordered, unique items dict {"name": "Praveen", "age": 39} Key-value pairs
Let's see some examples,
# List - Mutable and ordered fruits = ["apple", "banana", "cherry"] # Tuple - Immutable and ordered coordinates = (10.0, 20.5) # Set - Unordered, unique elements unique_numbers = {1, 2, 3, 2} # Dictionary - Key-value pairs person = {"name": "Praveen", "age": 39}
Key Characteristics:
-
List (
list):- Defined with square brackets []
- Items are ordered and can be changed
- Allows duplicates
-
Tuple (tuple):
- Defined with parentheses ()
- Ordered like a list, but cannot be modified (immutable)
-
Set (set):
- Defined with curly braces {} (like a dictionary but without key-value pairs)
- Unordered
- Does not allow duplicates
-
Dictionary (dict):
- Stores key-value pairs
- Defined with curly braces and colons {key: value}
- Keys must be unique
Accessing Elements:
print(fruits[0]) # List indexing: apple print(coordinates[1]) # Tuple indexing: 20.5 print("banana" in fruits) # Membership check: True print(person["name"]) # Access by key: Praveen
Use the type() function to confirm the data structure:
print(type(fruits)) # <class 'list'> print(type(coordinates))# <class 'tuple'> print(type(unique_numbers)) # <class 'set'> print(type(person)) # <class 'dict'>
Lists
List Slicing
myList=[1,2,3,4,5] print(myList[3:]) # It prints [4, 5] print(myList[0:6:2]) # It prints [1, 3, 5] print(myList[0:6:3]) # It prints [1, 4] print(myList[::2]) # It prints [1, 3, 5] print(list(range(10))) # It prints [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Modifying Lists
myList = [1,2,3,4] myList.append(5) print(myList) # It prints [1, 2, 3, 4, 5] myList.insert(3,8) print(myList) # It prints [1, 2, 3, 8, 4, 5] myList.remove(8) print(myList) # It prints [1, 2, 3, 4, 5] myList.pop() print(myList) # It prints [1, 2, 3, 4] print(len(myList)) # It prints 4 a = [1,2,3,4,5] b = a a.append(6) print(b) # It prints [1, 2, 3, 4, 5, 6] print(a) # It prints [1, 2, 3, 4, 5, 6] a = [1,2,3,4,5] b = a.copy() a.append(6) print(b) # It prints [1, 2, 3, 4, 5] print(a) # It prints [1, 2, 3, 4, 5, 6]
Sets
mySet = {'a','b','c','d'} print(mySet) # It prints {'a', 'b', 'd', 'c'} or in any order, as sets do not maintain order mySet = set({'a','b','c','d'}) print(mySet) # It prints {'a', 'b', 'd', 'c'} myList = ['a','b','c','d','c', 'b'] myList = list(set(myList)) print(myList) # It removes duplicates and prints ['a', 'b', 'd', 'c'] or in any order mySet.add('e') print(mySet) # It prints {'c', 'd', 'a', 'e', 'b'} or in any order print('a' in mySet) # It prints True print('p' in mySet) # It prints False print(len(mySet)) # It prints 5 mySet.discard('a') print(mySet) # It prints {'c', 'd', 'e', 'b'} or in any order
Tuples
A tuple is similar to a list, but it is declared using parentheses () instead of square brackets [].
Tuples are immutable, meaning their elements cannot be changed after creation.
myTuple = ('a','b','c','d') print(myTuple) # It prints ('a', 'b', 'c', 'd')
Why we use Tuples?
Let's say we are building a delivery tracking app. We need to store the GPS coordinates (latitude, longitude) of delivery locations. Since these coordinates should not be changed once recorded, a tuple is perfect.
# List of delivery locations as (latitude, longitude) tuples delivery_locations = [ (37.7749, -122.4194), # San Francisco (34.0522, -118.2437), # Los Angeles (40.7128, -74.0060), # New York ] # Display delivery locations for index, location in enumerate(delivery_locations, start=1): print(f"Delivery {index} Location: Latitude = {location[0]}, Longitude = {location[1]}")
Output
Delivery 1 Location: Latitude = 37.7749, Longitude = -122.4194 Delivery 2 Location: Latitude = 34.0522, Longitude = -118.2437 Delivery 3 Location: Latitude = 40.7128, Longitude = -74.0060
Why Use Tuples Here?
- Coordinates should not change — tuples ensure immutability.
- Tuples use less memory than lists.
- We are not performing operations that require mutability.
Dictionaries
A dictionary in Python is a collection of key-value pairs, where each key is unique and maps to a specific value.
Let's see an example, imagine we are building a student management system where we store and retrieve student details.
# Dictionary of student records student_records = { "S101": {"name": "Praveen", "grade": "A", "age": 39}, "S102": {"name": "Ravi", "grade": "B", "age": 38}, "S103": {"name": "Praneeth", "grade": "A", "age": 40} } # Access a specific student's details student_id = "S102" if student_id in student_records: print(f"Student Name: {student_records[student_id]['name']}") print(f"Grade: {student_records[student_id]['grade']}") else: print("Student not found.") # Add a new student student_records["S104"] = {"name": "Divya", "grade": "C", "age": 34} # Update an existing student's grade student_records["S103"]["grade"] = "A+" # Remove a student student_records.pop("S103") # Display all student records print("\nAll Student Records:") for sid, info in student_records.items(): print(f"ID: {sid}, Name: {info['name']}, Grade: {info['grade']}, Age: {info['age']}")
Output
Student Name: Ravi Grade: B All Student Records: ID: S101, Name: Praveen, Grade: A, Age: 39 ID: S102, Name: Ravi, Grade: B, Age: 38 ID: S104, Name: Divya, Grade: C, Age: 34