DSPython Logo DSPython

Data Structures

Learn about Lists, Tuples, Dictionaries, and Sets.

Python Basics Beginner 30 min

📋 Topic 1: Lists

A List is a collection which is ordered and changeable (mutable). It allows duplicate members. In Python, lists are written with square brackets [].

🎯 List Characteristics:

  • Ordered: Items have a defined order
  • Mutable: Can be changed after creation
  • Allows duplicates: Same items can appear multiple times
  • Indexed: Access items using index positions

💻 List Operations & Methods

# Creating a list
fruits = ["apple", "banana", "cherry"]
print(fruits)

# Accessing items (indexing starts at 0)
print(fruits[0]) # Output: apple

# Changing an item
fruits[1] = "orange"
print(fruits) # Output: ['apple', 'orange', 'cherry']

# Adding an item
fruits.append("mango")
print(fruits) # Output: ['apple', 'orange', 'cherry', 'mango']

# Removing an item
fruits.remove("cherry")
print(fruits) # Output: ['apple', 'orange', 'mango']

# Length of a list
print(len(fruits)) # Output: 3

💡 Common List Methods:

  • append() - Add item to end
  • insert() - Insert item at position
  • remove() - Remove first occurrence
  • pop() - Remove item at index
  • sort() - Sort the list
  • reverse() - Reverse the list

🎯 Try It Yourself:

Create a list of numbers and practice operations:

numbers = [5, 2, 8, 1, 9]
numbers.append(4)
numbers.sort()
numbers.insert(2, 7)
print(numbers)
print("Length:", len(numbers))

🔒 Topic 2: Tuples

A Tuple is a collection which is ordered and unchangeable (immutable). It allows duplicate members. In Python, tuples are written with round brackets ().

⚡ Key Difference:

Lists [] can be changed. Tuples () cannot be changed after creation.

💻 Tuple Operations

# Creating a tuple
colors = ("red", "green", "blue")
print(colors)

# Accessing items
print(colors[1]) # Output: green

# Slicing tuples
print(colors[0:2]) # Output: ('red', 'green')

# Trying to change an item (This will cause an ERROR!)
# colors[0] = "yellow" # <-- TypeError: 'tuple' object does not support item assignment

# Tuple with one element (notice the comma)
single_item = ("hello",)
print(type(single_item)) # Output: <class 'tuple'>

💡 When to Use Tuples:

  • When you want immutable data
  • For fixed collections that shouldn't change
  • As dictionary keys (lists can't be keys)
  • For data integrity - prevents accidental changes
  • Faster than lists for iteration

🎯 Try It Yourself:

Create coordinates as tuples and access them:

point1 = (3, 5)
point2 = (7, 2)

print("Point 1:", point1)
print("X coordinate:", point1[0])
print("Y coordinate:", point1[1])
# point1[0] = 10 # This would cause an error!

🗂️ Topic 3: Dictionaries

A Dictionary is a collection which is unordered (in older Python versions), changeable (mutable) and indexed. They store data in key: value pairs.

🎯 Dictionary Characteristics:

  • Key-Value Pairs: Store data as key:value
  • Unordered: No guaranteed order (Python 3.7+ maintains insertion order)
  • Mutable: Can be changed after creation
  • No Duplicate Keys: Keys must be unique

💻 Dictionary Operations

# Creating a dictionary
person = {
"name": "Vinay",
"age": 28,
"city": "Hyderabad"
}
print(person)

# Accessing a value using its key
print(person["name"]) # Output: Vinay

# Changing a value
person["age"] = 30
print(person)

# Adding a new key:value pair
person["job"] = "Developer"
print(person)

# Removing a key:value pair
person.pop("city")
print(person)

# Getting all keys and values
print(person.keys()) # Output: dict_keys(['name', 'age', 'job'])
print(person.values()) # Output: dict_values(['Vinay', 30, 'Developer'])

💡 Common Dictionary Methods:

  • get() - Safe way to access values
  • keys() - Get all keys
  • values() - Get all values
  • items() - Get key-value pairs
  • update() - Merge dictionaries
  • pop() - Remove specific key

🎯 Try It Yourself:

Create a student dictionary and practice operations:

student = {
"name": "Priya",
"grade": "A",
"subjects": ["Math", "Science"]
}
student["age"] = 20
print("Name:", student.get("name"))
print("All keys:", student.keys())

🔍 Topic 4: Sets

A Set is a collection which is unordered and unindexed. Most importantly, sets do not allow duplicate members. Sets are written with curly brackets {}.

🎯 Set Characteristics:

  • Unordered: No defined order
  • No Duplicates: Automatically removes duplicates
  • Unindexed: Cannot access by index position
  • Mutable: Can add/remove items
  • Mathematical Operations: Union, intersection, difference

💻 Set Operations

# Creating a set (notice the duplicates are removed)
my_set = {"apple", "banana", "cherry", "apple"}
print(my_set) # Output: {'banana', 'cherry', 'apple'}

# Adding an item
my_set.add("orange")
print(my_set)

# Removing an item
my_set.remove("banana")
print(my_set)

# Checking if an item is in the set
print("apple" in my_set) # Output: True

# Set operations
set1 = {1, 2, 3}
set2 = {2, 3, 4}
print(set1 | set2) # Union: {1, 2, 3, 4}
print(set1 & set2) # Intersection: {2, 3}
print(set1 - set2) # Difference: {1}

💡 Common Set Methods:

  • add() - Add element to set
  • remove() - Remove element (error if not found)
  • discard() - Remove element (no error if not found)
  • union() - Combine sets
  • intersection() - Find common elements
  • difference() - Find elements in one set but not other

🎯 Try It Yourself:

Remove duplicates from a list using sets:

numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print("Original:", numbers)
print("Unique:", unique_numbers)
print("Is 3 in set?", 3 in unique_numbers)