Python Control Flow and Data Structures: Loops, Lists, and Sets

Posted by Anonymous and classified in Computers

Written on in English with a size of 10.27 KB

Python Control Flow: Loops and Branching

Python provides powerful structures for iteration (loops) and flow control (branching statements) that allow you to execute blocks of code repeatedly or conditionally.

Python Loop Statements

Loops are used to execute a block of code multiple times. The main loop types in Python are while and for.

1. The while Loop

The while loop repeatedly executes a block of statements as long as a given condition is True.

  • Syntax:

    while condition:
    # statement(s) to be executed

  • Key Point: You must ensure that the condition eventually becomes False to avoid an infinite loop. This is typically done by modifying a variable within the loop body.

Example:

count = 0
while count < 3:
print(f"Count is {count}")
count += 1

Output:
Count is 0
Count is 1
Count is 2

2. The for Loop

The for loop is used to iterate over a sequence (like a list, tuple, string, or dictionary) or other iterable objects.

  • Syntax:

    for item in iterable:
    # statement(s) to be executed for each item

  • Iterable: Any object capable of returning its members one at a time.

Example (Iterating over a list):

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")

Output:
I like apple
I like banana
I like cherry

3. The range() Function

The range() function is often used with the for loop to generate a sequence of numbers.

  • Syntax Variations:
    • range(stop): Generates numbers from 0 up to (but not including) stop.
    • range(start, stop): Generates numbers from start up to (but not including) stop.
    • range(start, stop, step): Generates numbers from start up to stop, incrementing by step.

Example:

# range(5) -> 0, 1, 2, 3, 4
for i in range(5):
print(i) # Prints 0, 1, 2, 3, 4

4. Nested Loop Structures

A nested loop is a loop inside another loop. The inner loop executes completely for every single iteration of the outer loop.

Example (Creating a multiplication table):

for i in range(1, 3):       # Outer loop (i=1, then i=2)
for j in range(1, 3):   # Inner loop (j=1, then j=2)
print(f"{i} x {j} = {i * j}")

Output:
1 x 1 = 1
1 x 2 = 2
2 x 1 = 2
2 x 2 = 4

5. Inserting Conditions in Loops

You can use conditional statements (if/elif/else) inside loops to execute certain code only when a specific condition is met during an iteration. Conversely, you can also use a loop inside a conditional block.

Example (Using if inside a for loop):

numbers = [1, 2, 3, 4, 5, 6]
for num in numbers:
if num % 2 == 0: # Check if the number is even
print(f"{num} is even.")
else:
print(f"{num} is odd.")

Python Branching Statements (Loop Control)

Branching statements (also known as loop control statements) are used to change the execution flow from its normal sequence.

1. break Statement

The break statement immediately terminates the current loop (both for and while) and transfers execution to the statement immediately following the loop.

Example:

for letter in "Python":
if letter == "h":
break
print(letter)

Output:
P
y
t

2. continue Statement

The continue statement skips the rest of the code inside the current iteration of the loop and proceeds to the next iteration.

Example:

for i in range(5): # 0, 1, 2, 3, 4
if i == 2:
continue # Skips the print statement for i=2
print(i)

Output:
0
1
3
4

3. pass Statement

The pass statement is a null operation; nothing happens when it executes. It is often used as a placeholder when a statement is syntactically required but you do not want any code to execute.

Example:

for item in [1, 2, 3]:
if item == 2:
pass # To be implemented later (e.g., logging)
else:
print(item)

Output:
1
3

Python Data Structures: Lists, Tuples, and Sets

Python Lists: Mutable Sequences

Python lists are versatile data structures used to store an ordered collection of items that can be of any data type. You can create a list using square brackets ([]) or the list() constructor. For example, fruits = ["apple", "banana", "cherry"] creates a list with three string elements, while nums = list((1, 2, 3)) converts a tuple into a list. Lists are mutable, meaning you can modify their contents after creation. For instance, you can update an element by index: fruits[1] = "orange" changes "banana" to "orange".

Adding Elements to Lists

To add elements, lists provide methods such as:

  • append(): Adds an item at the end (e.g., fruits.append("date")).
  • extend(): Adds multiple items from another iterable (e.g., fruits.extend(["fig", "grape"])).
  • insert(): Places an item at a specific index (e.g., fruits.insert(1, "blueberry")).

You can also update multiple elements simultaneously using slicing, like fruits[1:3] = ["blackberry", "kiwi"].

Deleting Elements from Lists

For deleting elements, Python lists offer several options:

  • The del statement: Removes elements by index or slice (e.g., del fruits[0] removes the first element).
  • The remove() method: Deletes the first occurrence of a value (e.g., fruits.remove("kiwi")).
  • The pop() method: Removes and returns an element at a specific index, or the last element if no index is provided (e.g., last = fruits.pop() removes and returns the last fruit).

To clear all elements, you can use fruits.clear().

Essential List Methods and Functions

Python lists come with many built-in functions and methods that facilitate manipulation, including:

  • len(): To get the number of items.
  • max() and min(): To find the largest and smallest elements.
  • sum(): To add numeric items.
  • count(): To find how many times a value occurs.
  • index(): To find the position of a value.

Lists can be sorted in place with sort() or you can create a new sorted list using the built-in sorted() function. Additionally, reverse() reverses the order of elements, and copy() creates a shallow copy of the list.

Python Tuples and Sets

Both Tuples and Sets are core collection types in Python, each serving distinct purposes based on their inherent properties of order and mutability.

Python Tuples (Immutable Sequences)

A Tuple is an ordered and immutable sequence of items. Tuples are created using a comma-separated sequence of values, typically enclosed in parentheses (()), such as my_tuple = (1, "a", 3.14). Since tuples are immutable, you cannot update, add, or delete elements directly. The common workaround for an "update" is to convert the tuple to a list (list(my_tuple)), modify the list, and then convert it back to a tuple (tuple(modified_list)). Tuples can be joined (concatenated) using the addition operator (+), which creates a new tuple (e.g., t1 + t2). The primary built-in methods are limited to those that read information: count(value), which returns the number of occurrences of a value, and index(value), which returns the index of the first occurrence.

Python Sets (Unique, Unordered Collections)

A Set is an unordered collection of unique and immutable items. Sets are mutable containers, meaning you can add or remove items, but the items themselves must be immutable (like numbers or strings). Sets are created using curly braces ({}) (e.g., my_set = {1, 2, 3}) or the set() constructor for an empty set. To add items, you use add(item) for a single item or update(iterable) for multiple items. To remove items, you can use remove(item) (raises an error if not present) or the safer discard(item) (does nothing if not present). You can also remove an arbitrary item using pop() or remove all items with clear().

Set Operations and Comparison Methods

Sets excel at joining and comparison using set methods (often corresponding to mathematical set operations). The key joining/comparison methods are:

  • union() (|): To combine elements.
  • intersection() (&): To find common elements.
  • difference() (-): To find elements in the first set but not the second.
  • symmetric_difference() (^): To find elements present in either set but not both.

Other methods include issubset() and issuperset().

Related entries: