book-openLoops, Lists, Dictionaries

The following examples show you how to manipulate files further using for loops, list comprehension and dictionaries.

For Loops

For loops help iterate over data in lists and files.

Syntax
Description

for item in sequence:

Loops through items in a sequence (list, string, etc.).

for i in range(start, stop, step):

Loops a specific number of times, from start to stop.

Example:

# Loop through a list
names = ["Alice", "Bob", "Charlie"]
for name in names:
    print(name)  # Prints each name in the list

List Comprehension

List comprehensions allow you to create new lists from existing ones, often in a single line.

Syntax
Description

[expression for item in iterable]

Creates a list with an expression applied to each item in the iterable.

[expression for item in iterable if condition]

Creates a list with a conditional check.

Examples:


Dictionaries

Dictionaries store data as key-value pairs. Useful for mapping relationships, like student names to ages.

Syntax
Description

dict = {key1: value1, key2: value2}

Creates a dictionary with key-value pairs.

dict[key]

Accesses the value associated with a key.

dict[key] = value

Adds or updates a key-value pair in the dictionary.

.items()

Returns the dictionary as key-value pairs.

.keys()

Returns the keys from the dictionary.

.values()

Returns the values from the dictionary.

Example:

Iterating Over Dictionaries

To loop through a dictionary, you can use for loops with .items(), .keys(), or .values().

Example:

Last updated