0% found this document useful (0 votes)
9 views9 pages

Sequence - Mapping - Branching Self Made Notes

The document provides an overview of sequence types in Python, including lists, tuples, strings, ranges, and byte sequences, highlighting their mutability, order, and key operations. It also covers dictionaries as a mapping type, detailing their structure, mutability, and common operations. Additionally, it explains conditional branching in Python programming, including if statements, else and elif statements, and the use of logical and comparison operators.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views9 pages

Sequence - Mapping - Branching Self Made Notes

The document provides an overview of sequence types in Python, including lists, tuples, strings, ranges, and byte sequences, highlighting their mutability, order, and key operations. It also covers dictionaries as a mapping type, detailing their structure, mutability, and common operations. Additionally, it explains conditional branching in Python programming, including if statements, else and elif statements, and the use of logical and comparison operators.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Sequence Types in Python

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

 Mutable: Elements can be added, removed, or changed.


 Ordered: The elements have a defined order, and this order will not change unless
explicitly modified.
 Indexing: Supports both positive and negative indices, where negative indexing starts
from the end.
 Methods:
o append(): Adds an item to the end.
o remove(): Removes a specific item.
o pop(): Removes and returns the last item or the item at a given index.
o sort(): Sorts the list in place.

my_list = [1, 2, 3, 4, 5]
my_list.append(6)

2. Tuples

 Immutable: Once created, elements cannot be changed, added, or removed.


 Ordered: Like lists, tuples maintain the order of their elements.
 Use cases: Best for fixed collections of items.
 Methods:
o count(): Returns the number of times a specified value occurs in a tuple.
o index(): Returns the index of the first occurrence of a specified value.

my_tuple = (1, 2, 3, 4)
first_item = my_tuple[0]

3. Strings

 Immutable: Similar to tuples, strings cannot be changed once created.


 Ordered: The characters in a string maintain the order of their appearance.
 Indexing: Supports positive and negative indexing.
 Slicing: Substrings can be extracted using slicing.
 Methods:
o upper(): Converts a string to uppercase.
o lower(): Converts a string to lowercase.
o split(): Splits the string into a list of substrings.
o replace(): Replaces a specified substring with another.

my_string = "Hello, Python!"


upper_string = my_string.upper()
4. Ranges

 Immutable: Range objects represent sequences of numbers but cannot be modified.


 Used in loops: Commonly used for iteration in for loops.
 Parameters: range(start, stop, step) where start is inclusive, stop is
exclusive, and step is optional.

for i in range(1, 10, 2):


print(i)

5. Byte Sequences

 Bytes: Immutable sequences of integers in the range of 0-255.


o Immutable: Cannot be modified.
o Can be used to represent binary data (e.g., images or network protocols).

my_bytes = b'hello'

 Bytearray: Mutable version of bytes.


o Mutable: Can be changed after creation.

my_bytearray = bytearray(b'hello')
my_bytearray[0] = 72

Key Operations on Sequence Types:

 Indexing: Access elements by their position, starting from 0.

my_list[0] # First element

 Slicing: Extract a part of the sequence.

my_list[1:3] # Elements from index 1 to 2


new_list = [1, 2] + [3, 4]

 Repetition: Repeat elements using the * operator.

repeated_list = [1, 2] * 3

Summary:

 Lists are mutable and versatile.


 Tuples are immutable and used for fixed collections.
 Strings are immutable sequences of characters.
 Ranges represent sequences of numbers and are often used in loops.
 Bytes and Bytearrays deal with binary data.
Mapping and Tuple Types in Python: Dictionaries and Tuples

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:

my_dict = {"name": "Alice", "age": 25, "city": "New York"}

Common Dictionary Operations:

 Accessing Values: Use the key to access the corresponding value.

my_dict["name"] # Returns 'Alice'

 Adding/Modifying Values: You can add a new key-value pair or modify an existing
one.

my_dict["age"] = 26 # Modifies the value for the key 'age'


my_dict["country"] = "USA" # Adds a new key-value pair

 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"])

 Iterating Over a Dictionary:


o Keys: Use keys() to get an iterable view of the dictionary's keys.
o Values: Use values() to get the dictionary’s values.
o Key-Value Pairs: Use items() to get key-value pairs as tuples.

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"})

 clear(): Removes all items from the dictionary.


 copy(): Returns a shallow copy of the dictionary.

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.

my_tuple = (1, "hello", 3.14)

Common Tuple Operations:

 Accessing Elements: Tuples use zero-based indexing, just like lists.

first_item = my_tuple[0] # Accesses the first item

 Slicing: You can slice a tuple to create a new tuple.

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

Key Features of Tuples:

 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:

my_tuple = (10, 20, 30)


second_item = my_tuple[1] # Accesses the second element

Key Differences Between Dictionaries and Tuples:

 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 in Python Programming

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

 The if statement is the most basic form of conditional branching.


 It evaluates a condition (expression) and executes a block of code only if the
condition is True.
 Syntax:

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")

5. Ternary Conditional Operator

 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:

value_if_true if condition else value_if_false

 Example:

x = 5
result = "Greater than 10" if x > 10 else "Less than or equal to 10"
print(result)

6. Logical Operators in Conditional Branching

 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

 Conditional statements often involve comparison operators:


o ==: Equal to.
o !=: Not equal to.
o >: Greater than.
o <: Less than.
o >=: Greater than or equal to.
o <=: Less than or equal to.
 Example:

if x >= 5:
print("x is greater than or equal to 5")

8. pass Statement

 Sometimes you need to write a conditional block with no action (e.g., as a


placeholder). In such cases, the pass statement is used.
 Example:

if x > 5:
pass # Do nothing for now

9. match Statement (Python 3.10+)

 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:

 The if-elif-else statements allow for conditional branching based on logical


conditions.
 Logical operators like and, or, and not help combine multiple conditions.
 The ternary operator allows concise one-liner condition checks.
 Comparison operators and logical operators are key to defining conditions.
 Nested conditionals allow complex decision-making processes.

You might also like