Sequence - Mapping - Branching Self Made Notes
Sequence - Mapping - Branching Self Made Notes
In Python, sequences are an essential data structure that stores multiple items, which can be
indexed, sliced, and iterated over. Sequence types allow grouping of data in various ways.
Below are the main sequence types in Python:
1. Lists
my_list = [1, 2, 3, 4, 5]
my_list.append(6)
2. Tuples
my_tuple = (1, 2, 3, 4)
first_item = my_tuple[0]
3. Strings
5. Byte Sequences
my_bytes = b'hello'
my_bytearray = bytearray(b'hello')
my_bytearray[0] = 72
repeated_list = [1, 2] * 3
Summary:
1. Dictionaries
Definition: Dictionaries are collections of key-value pairs where each key maps to a
value. It is the most common mapping type in Python.
Mutable: The contents of a dictionary (i.e., the key-value pairs) can be changed after
creation. You can add, modify, or delete key-value pairs.
Unordered: While dictionaries are unordered prior to Python 3.7, in Python 3.7 and
later, dictionaries maintain the insertion order.
Keys: Keys in dictionaries must be unique and immutable (like strings, numbers, or
tuples), while the values can be of any data type (mutable or immutable).
Hashable Keys: The keys must be hashable, meaning they should have a hash value
that does not change during the lifetime of the dictionary.
Syntax:
Adding/Modifying Values: You can add a new key-value pair or modify an existing
one.
Removing Key-Value Pairs: Use del or the pop() method to remove a key-value
pair.
del my_dict["city"]
value = my_dict.pop("age")
Checking for Keys: Use the in keyword to check if a key exists in the dictionary.
if "name" in my_dict:
print(my_dict["name"])
python
Copy code
for key, value in my_dict.items():
print(key, value)
Dictionary Methods:
get(): Returns the value for a specified key, with an optional default if the key is not
found.
python
Copy code
my_dict.get("name", "Not found")
update(): Updates the dictionary with key-value pairs from another dictionary or
iterable.
python
Copy code
my_dict.update({"age": 30, "city": "San Francisco"})
Example:
person = {
"name": "John",
"age": 30,
"profession": "Engineer"
}
2. Tuples
Definition: Tuples are immutable sequences in Python, often used to store a fixed
collection of items. Unlike dictionaries, tuples are not mapping types but are useful to
discuss because they are commonly used as keys in dictionaries (because they are
immutable and hashable).
Immutable: Once a tuple is created, you cannot change its values (no item
assignment, adding, or removal).
Ordered: Tuples maintain the order of elements, and elements are indexed.
Heterogeneous: Tuples can store elements of different data types, just like lists.
Syntax: Defined using parentheses () with elements separated by commas.
sub_tuple = my_tuple[1:3]
Tuple Packing and Unpacking: You can assign multiple values into a tuple
(packing), and extract them back (unpacking).
packed_tuple = ("John", 25, "Engineer")
name, age, profession = packed_tuple # Unpacking
Immutable: Since tuples are immutable, they are generally faster than lists and are
often used for fixed collections of items.
Hashable: Tuples can be used as dictionary keys or elements of a set, unlike lists.
Methods:
o count(): Returns the number of times a value appears in a tuple.
o index(): Returns the first index of a value.
Example:
Mutability:
o Dictionaries are mutable (you can add, modify, and delete key-value pairs).
o Tuples are immutable (you cannot change them after creation).
Usage:
o Dictionaries are used to map unique keys to values.
o Tuples are used to store ordered collections of items, often when the data
should not change.
Structure:
o Dictionaries are unordered key-value pairs.
o Tuples are ordered collections of values.
Conditional branching allows a program to execute certain pieces of code based on whether
specific conditions are true or false. It is fundamental for controlling the flow of a program,
enabling decision-making, and responding to different inputs or conditions dynamically.
1. if Statement
if condition:
# Code block to execute if the condition is True
Example:
x = 10
if x > 5:
print("x is greater than 5")
2. else Statement
The else statement is used to define an alternative block of code to be executed if the
condition in the if statement is False.
Syntax:
if condition:
# Code block if condition is True
else:
# Code block if condition is False
Example:
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
3. elif Statement
The elif (short for "else if") statement is used to check multiple conditions in a
sequence. It allows additional conditions to be tested if the previous conditions are
False.
You can have multiple elif statements, but only the first one that evaluates to True
will execute.
Syntax:
if condition1:
# Code block if condition1 is True
elif condition2:
# Code block if condition2 is True
else:
# Code block if none of the above conditions are True
Example:
x = 8
if x > 10:
print("x is greater than 10")
elif x == 8:
print("x is equal to 8")
else:
print("x is less than 8")
4. Nested if Statements
You can nest if, elif, and else statements inside one another to create more
complex branching logic. This allows for multiple layers of decision-making.
Syntax:
if condition1:
if condition2:
# Code block if both condition1 and condition2 are True
else:
# Code block if condition1 is True but condition2 is False
else:
# Code block if condition1 is False
Example:
x = 10
y = 20
if x > 5:
if y > 15:
print("Both x and y are large")
else:
print("x is large but y is not")
else:
print("x is not large")
Python supports a concise syntax for simple conditional expressions, also called the
ternary operator. It allows writing an if-else condition in a single line.
Syntax:
Example:
x = 5
result = "Greater than 10" if x > 10 else "Less than or equal to 10"
print(result)
You can combine multiple conditions using logical operators like and, or, and not to
create complex conditions.
and: True if both conditions are True.
or: True if at least one of the conditions is True.
not: Inverts the Boolean value.
Example:
x = 10
y = 5
if x > 5 and y < 10:
print("Both conditions are true")
7. Comparison Operators
if x >= 5:
print("x is greater than or equal to 5")
8. pass Statement
if x > 5:
pass # Do nothing for now
The match statement, introduced in Python 3.10, is a form of pattern matching, often
compared to the switch statement in other programming languages. It allows more
advanced branching based on the structure and value of data.
Syntax:
match variable:
case pattern1:
# Code block if pattern1 matches
case pattern2:
# Code block if pattern2 matches
case _:
# Default case if no other patterns match
Example:
status = 404
match status:
case 200:
print("OK")
case 404:
print("Not Found")
case 500:
print("Server Error")
case _:
print("Unknown status")
Summary: