Day 5: Data Structures: Lists and Dictionaries
Welcome to Day 5 of our 90-day journey to learn core Python! Yesterday, we explored functions and their importance in organizing and reusing code. Today, we’ll dive into data structures, specifically lists and dictionaries. Let’s get started!
Lists: Storing Collections of Data
A list is a versatile data structure that allows us to store and manipulate collections of data. Lists are ordered, mutable, and can contain elements of different data types. Let’s see some examples:
fruits = ['apple', 'banana', 'orange'] # List of strings
numbers = [1, 2, 3, 4, 5] # List of integers
mixed = ['apple', 1, True, 3.14] # List with mixed data types
Lists provide various methods to manipulate and access elements, such as appending, removing, and slicing. Explore these methods to unleash the power of lists in your programs!
Dictionaries: Key-Value Pairs
Dictionaries are another essential data structure in Python. Unlike lists, dictionaries store data in key-value pairs. Keys are unique identifiers, and their associated values can be of any data type. Let’s see an example:
person = {'name': 'John', 'age': 25, 'city': 'New York'} # Dictionary
We can access values by their corresponding keys and perform operations like adding, modifying, or deleting key-value pairs. Dictionaries are particularly useful when working with structured data.
Indexing and Slicing
Both lists and dictionaries support indexing and slicing to access specific elements or subsets of data. Indexing starts from 0 in Python. Here’s an example:
my_list = [1, 2, 3, 4, 5]
print(my_list[0]) # Output: 1
my_dict = {'name': 'John', 'age': 25}
print(my_dict['name']) # Output: 'John'
Slicing allows us to extract portions of a list or dictionary by specifying a range of indices. Experiment with slicing to extract the data you need!
Conclusion
Congratulations on completing Day 5 of our Python learning journey! Today, we explored two important data structures: lists and dictionaries. Lists provide a flexible way to store collections of data, while dictionaries allow us to work with key-value pairs.
Take some time to practice using lists and dictionaries in your code. Tomorrow, on Day 6, we’ll delve into file handling, allowing us to read from and write to files using Python.
Keep up the great work, and I’ll see you tomorrow for Day 6! Happy coding! 🚀
Note: This blog post is part of a 90-day series to teach core Python programming from scratch. If you missed any previous days, you can find them in the series index here.