Lists and Loops


Lists

In Python, a list is a collection that stores multiple pieces of information. It’s like having a backpack that can hold various items.

1. Creating Lists and Accessing Elements:

Creating a list is as simple as putting items between square brackets, separated by commas. You can access individual items using their positions, called indices.

Example: Creating Lists and Accessing Elements

fruits = ["apple", "banana", "orange"]
print(fruits[0])   # Output: apple
print(fruits[2])   # Output: orange

2. Modifying Lists:

Lists are dynamic so you can add, remove, and even change items as you go along.

Example: Modifying Lists

# Adding an item to the end of the list
fruits.append("grape")

# Removing an item by value
fruits.remove("banana")

Loops:

Loops are your trusty sidekicks for performing repetitive tasks. There are different types of loops suited for different scenarios as shown below:

1. For Loops:

For loops help you dance through a set of actions for each item in a list, making repetitive tasks a breeze.

Example: Using a For Loop

Using the list of fruits we created earlier, let’s see the power of for loops.

for fruit in fruits:
    print("I love", fruit + "s")

2. While Loops:

While loops keep performing actions as long as a certain condition is true.

Example: Using a While Loop

count = 0
while count < 5:
    print("Count:", count)
    count += 1

4. Range:

The range function and nested for loops give you control over how many times your actions repeat.

Example:

# Using range to repeat a task
for number in range(3):
    print("Count:", number)

5. Nested Loops:

Nested loops are like loops within loops.

Example: Nested For Loops

for x in range(3):
    for y in range(2):
        print("x:", x, "y:", y)

Leave a Reply

Your email address will not be published. Required fields are marked *