Server Info & Course Info
Like a shopping list that can hold multiple items
# Shopping list example
groceries = ["apples", "milk", "eggs", "bread"]
print("My shopping list:", groceries)
[]
colors = ["red", "green", "blue"]
list() constructor
numbers = list((1, 2, 3)) # Converts tuple to list
squares = [x**2 for x in range(5)]
# [0, 1, 4, 9, 16]
word = list("hello")
# ['h', 'e', 'l', 'l', 'o']
Positive indexing:
games = ["Mario", "Zelda", "Pokémon"]
print(games[0]) # Mario
print(games[-1]) # Pokémon (negative index)
Get sub-lists with [start:end]
months = ["Jan", "Feb", "Mar", "Apr", "May"]
print(months[1:3]) # ['Feb', 'Mar']
print(months[:2]) # First two: ['Jan', 'Feb']
print(months[3:]) # Last two: ['Apr', 'May']
append() and insert()
todo = ["wake up"]
todo.append("brush teeth") # Add to end
todo.insert(1, "make bed") # Insert at position 1
print(todo) # ['wake up', 'make bed', 'brush teeth']
remove() and pop()
pets = ["cat", "dog", "hamster"]
pets.remove("dog") # Remove by value
last = pets.pop() # Remove last item
print(pets) # ['cat']
print(last) # 'hamster'
sort() method
scores = [88, 92, 75, 100]
scores.sort()
print(scores) # [75, 88, 92, 100]
# Reverse sort
scores.sort(reverse=True)
print(scores) # [100, 92, 88, 75]
Store multiple students’ scores
students = ["Alice", "Bob", "Charlie"]
scores = [88, 92, 75]
total = sum(scores)
average = total / len(scores)
print(f"Class average: {average}")
# Output: Class average: 85.0
Combine data with zip()
combined = []
i=0
while i<len(scores):
combined.append( [scores[i], students[i]] )
i=i+1
combined.sort()
print("Ranking:")
for one in combined:
print(f"{one[1]}: {one[0]}")

# Lists are mutable
fruits = ["apple", "banana", "cherry"]
fruits[0] = "avocado"
print(fruits) # Changes successfully
# Tuples are immutable (unchangeable)
colors = ("red", "green", "blue")
colors[0] = "pink"
# report error
Key difference:
📌 Tuples use () while lists use []
📌 Tuple elements cannot be changed after creation
Real-life examples of unchangeable data:
# Valid tuple usage
black = (0, 0, 0)
current_position = (37.7749, -122.4194)
Basic unpacking:
dimensions = (1920, 1080)
width, height = dimensions
print(f"Screen: {width}x{height}")
Swapping variables:
a = 5
b = 10
a, b = b, a
Ignoring values:
coordinates = (45, -73, 100)
lat, lon, _ = coordinates
Multiple assignment:
# Get first and last items
numbers = (3, 1, 4, 1, 5, 9)
first, *middle, last = numbers
Common mistake:
not_a_tuple = (42)
print(type(not_a_tuple)) # <class 'int'>
Correct way:
proper_tuple = (42,)
print(type(proper_tuple)) # <class 'tuple'>
Visual reminder:
❗ Always add comma for single items ❗
Simple example:
def circle_calc(radius):
area = 3.14 * radius ** 2
circumference = 2 * 3.14 * radius
return (area, circumference)
results = circle_calc(5)
print(f"Area: {results[0]}, Circumference: {results[1]}")
Better usage with unpacking:
area, circ = circle_calc(7)
print(f"Area is {area} units")
Perfect for:
# Valid dictionary key
locations = {
(40.7128, -74.0060): "New York",
(51.5074, -0.1278): "London"
}
Essential methods:
my_tuple = (1, 2, 3)
print(len(my_tuple)) # 3
print(2 in my_tuple) # True
print(my_tuple.index(2)) # 1
print(my_tuple.count(2)) # 1

# Think of dictionaries like phone contacts:
phone_book = {
"Alice": "555-1234",
"Bob": "555-5678",
"Charlie": "555-9012"
}
print(phone_book["Alice"]) # Outputs: 555-1234
student = {"name": "Emma", "age": 20, "major": "CS"}
colors = dict(red="#FF0000", green="#00FF00")
weekdays = dict([(1, "Mon"), (2, "Tue"), (3, "Wed")])
animal_sounds = {}
animal_sounds["dog"] = "Woof!" # Add new entry
animal_sounds["cat"] = "Mew" # Add another
animal_sounds["cat"] = "Meow" # Update existing
print(animal_sounds) # {'dog': 'Woof!', 'cat': 'Meow'}
del animal_sounds["dog"] # Delete entry
removed = animal_sounds.pop("cat")
print(removed) # "Meow"
print(animal_sounds) # Empty now
grades = {"Math": 90, "Science": 85}
print(grades.get("History", "Subject not found"))
# Outputs: Subject not found
nano translator.py
translator = {
"hello": "hola",
"goodbye": "adiós",
"thank you": "gracias"
}
word = input("Enter English word: ").lower()
translation = translator.get(word, "Translation not available")
print(f"Spanish: {translation}")
python3 translator.py
# input: hello
if translation == "Translation not available":
print("Please check spelling!")
print("Current dictionary words:", list(translator.keys()))
my_dict = {"a": 1, "b": 2}
print(my_dict.keys()) # dict_keys(['a', 'b'])
print(my_dict.values()) # dict_values([1, 2])
print(my_dict.items()) # dict_items([('a', 1), ('b', 2)])
nano movie_rating.py
movies = {
"Moana": 7.5,
"Toy Story": 8.6,
"Frozen": 8.5
}
movie = input("Enter movie title: ")
print(f"Rating: {movies.get(movie, 'Not in database')}/10")
mixed_example = {
1: "Number key",
(2,3): "Tuple key",
"list": ["can", "be", "value"]
}

# List vs Set comparison
fruits_list = ['apple', 'banana', 'apple', 'orange']
fruits_set = {'apple', 'banana', 'apple', 'orange'}
print(f"List: {fruits_list}") # Keeps duplicates
print(f"Set: {fruits_set}") # Auto-removes duplicates
# Removing duplicate votes
votes = ['Alice', 'Bob', 'Alice', 'Charlie', 'Bob']
unique_voters = set(votes)
print(f"Total votes: {len(votes)}")
print(f"Unique voters: {len(unique_voters)}")
# Common elements in both sets
art_students = {'Tom', 'Alice', 'Bob', 'Eve'}
music_students = {'Alice', 'Eve', 'John'}
both = art_students & music_students
print(f"Students in both clubs: {both}")
# Combine sets (no duplicates)
week1_customers = {'Alice', 'Bob'}
week2_customers = {'Bob', 'Charlie'}
all_customers = week1_customers | week2_customers
print(f"All customers: {all_customers}")
# Elements in first set not in second
available_colors = {'red', 'blue', 'green'}
used_colors = {'blue', 'yellow'}
remaining = available_colors - used_colors
print(f"Remaining colors: {remaining}")
nano vote.py
# Counting unique votes
votes = []
while True:
vote = input("Enter candidate name (or 'done'): ")
if vote.lower() == 'done':
break
votes.append(vote)
unique_votes = set(votes)
print(f"Candidates: {', '.join(unique_votes)}")
# Finding common friends
alice_friends = {'Bob', 'Charlie', 'Diana'}
bob_friends = {'Charlie', 'Diana', 'Eve'}
common = alice_friends & bob_friends
print(f"Common friends: {common}")
# Adding new friend
alice_friends.add('Eve')
print(f"Updated friends: {alice_friends}")
| Method | Example | Description |
|————-|—————————–|—————————–|
| add() | s.add('x') | Add element |
| remove() | s.remove('x') | Remove element |
| clear() | s.clear() | Empty the set |
| copy() | new_set = s.copy() | Create duplicate |
'a' in set
a = []
def add():
a.append(1)
add()
print(a)
a = set()
def add():
a.add(1)
add()
print(a)
a = {}
def add():
a[1]=1
add()
print(a)
a=0
def add():
a=a+1
add()
print(a)
# Create empty list
students = []
# Create student dictionary
student1 = {
"name": "Alice",
"age": 20,
"major": "Computer Science"
}
students.append(student1)
def add_student():
name = input("Enter name: ")
age = int(input("Enter age: "))
major = input("Enter major: ")
new_student = {
"name": name,
"age": age,
"major": major
}
students.append(new_student)
print("Student added!")
text = "apple banana orange apple pear orange apple ok yes yes ok no no want"
words = text.lower().split()
print(words)
word_counts = {}
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
print(word_counts)