Learn Python from Scratch 2023: Module 3
Module 3: Data Structures
3.1 Introduction to Data Structures:
Data structures are containers that hold data in an organized and efficient manner. In Python, there are four built-in data structures: lists, tuples, sets, and dictionaries.
3.2 Lists:
Lists are a collection of values that are ordered and changeable. They are defined by enclosing a comma-separated sequence of values in square brackets []. Here’s an example:
fruits = ["apple", "banana", "cherry"]
To access a specific element in a list, you can use indexing. Indexing starts at 0 in Python, so to access the first element of the fruits list, you would use the index 0:
print(fruits[0]) # Output: "apple"
You can also use negative indexing to access elements from the end of the list:
print(fruits[-1]) # Output: "cherry"
Lists are mutable, which means you can change their values. For example, you can add an element to the end of a list using the append() method:
fruits.append("orange")
print(fruits) # Output: ["apple", "banana", "cherry", "orange"]
3.3 Tuples:
Tuples are similar to lists, but they are immutable, which means you cannot change their values. They are defined by enclosing a comma-separated sequence of values in parentheses (). Here’s an example:
fruits = ("apple", "banana", "cherry")
You can access elements in a tuple using indexing, just like with lists:
print(fruits[0]) # Output: "apple"
However, you cannot change the values of a tuple:
fruits[0] = "orange" # This will result in an error
3.4: Sets
Sets are a collection of unique values that are unordered and unindexed. They are defined by enclosing a comma-separated sequence of values in curly braces {}. Here’s an example:
fruits = {"apple", "banana", "cherry"}
You cannot access elements in a set using indexing, but you can check if a value is in a set using the “in” keyword:
print("banana" in fruits) # Output: True
You can add elements to a set using the add() method:
fruits.add("orange")
print(fruits) # Output: {"apple", "banana", "cherry", "orange"}
Submodule 3.5
Dictionaries Dictionaries are a collection of key-value pairs that are unordered and changeable. They are defined by enclosing a comma-separated sequence of key-value pairs in curly braces {}, where each key-value pair is separated by a colon :. Here’s an example:
person = {"name": "John", "age": 30, "city": "New York"}
You can access the value of a specific key in a dictionary using indexing:
print(person["name"]) # Output: "John"
You can also change the value of a key:
person["age"] = 40
print(person) # Output: {"name": "John", "age": 40, "city": "New York"}
To add a new key-value pair to a dictionary, you can simply assign a value to a new key:
person["gender"] = "Male"
print(person) # Output: {"name