Python Basics Part 2
Title: Python for Beginners - Part 2
Title: Python Data Structures: Mastering Lists, Tuples, and Dictionaries
Lists: The Flexible Organizers
- What they are: Lists are ordered, mutable collections of items. Think of them as changeable shopping lists.
- Creating a list:
my_numbers = [1, 2, 3, 4] my_friends = ["Alice", "Bob", "Charlie"]
- Accessing items: Use zero-based indexing
print(my_numbers[0]) # Output: 1
- Changing items:
my_friends[1] = "Sarah"
- Common methods:
list.append(item)
– Adds an item to the endlist.insert(index, item)
– Inserts an item at a specific positionlist.remove(item)
– Removes the first occurrence of an item
Tuples: The Immutable Cousins
- What they are: Tuples are ordered, immutable collections of items. Think of them as fixed sets of coordinates.
- Creating a tuple:
coordinates = (10, 20) website_info = ("Python 101", "https://python101.com")
- Accessing items: Same indexing as lists
- Why immutable? Good for data that shouldn't change (like coordinates, configuration settings) and can make your code a bit safer.
Dictionaries: Key-Value Superstars
- What they are: Dictionaries store key-value pairs, like real-world dictionaries. Keys must be unique and immutable.
- Creating a dictionary:
student = {"name": "Alice", "age": 30, "courses": ["Math", "Science"]}
- Accessing values:
print(student["name"]) # Output: Alice
- Changing values:
student["age"] = 31
- Adding items:
student["city"] = "New York"
Let's Build Something Practical
How about a contact book application?
contacts = {
"Alice": {"phone": "123-456-7890", "email": "alice@email.com"},
"Bob": {"phone": "987-654-3210", "email": "bob@email.com"}
}
def add_contact():
# Code to get name, phone, email...
def find_contact():
# Code to search by name...
# Simple menu for the user...
Key Takeaways
- Choose wisely:
- Lists for ordered, changeable data
- Tuples for fixed, unchangeable data
- Dictionaries for mapping keys to values
Continue Your Exploration
- Advanced list operations: Slicing, sorting, list comprehensions
- More dictionary methods:
items()
,keys()
,values()
- Sets: Unordered collections of unique items (great for removing duplicates)