How to Code in Python: Part 5 — Lists, Indexing, and Looping with Power

Now that you’ve learned how to use conditionals and loops, it’s time to give your programs more flexibility using lists. Python lists are ordered, changeable, and can hold anything — numbers, strings, or even other lists.

🔢 Step 1: Creating and Using Lists

Lists are created using square brackets [], and each item is separated by a comma.

groceries = ["eggs", "milk", "bread"]
print(groceries)

You can access specific items in the list using their index. Remember, Python starts counting at 0.

print(groceries[0])  # Output: eggs
print(groceries[2])  # Output: bread

✂️ Step 2: Indexing and Slicing

Indexing gets a single item. Slicing gets a range of items:

numbers = [10, 20, 30, 40, 50]

print(numbers[1:4])   # [20, 30, 40]
print(numbers[:3])    # [10, 20, 30]
print(numbers[2:])    # [30, 40, 50]

🔍 Note: The slice [1:4] includes index 1, 2, and 3 — but not 4. Python slicing is inclusive:exclusive.

🧱 Step 3: Building Lists Dynamically

You can start with an empty list and add items using append():

my_list = []
my_list.append("alpha")
my_list.append("beta")
print(my_list)  # ['alpha', 'beta']

🔁 Step 4: Looping Through Lists

You can use a for loop to go through each item in a list:

for item in groceries:
    print("Need to buy:", item)

🧮 Step 5: Using enumerate() for Index Tracking

If you need both the index and value, use enumerate():

for index, item in enumerate(groceries):
    print(f"{index}: {item}")

🔗 Step 6: Looping Two Lists at Once with zip()

Want to pair two lists together? zip() lets you loop through both at the same time:

names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]

for name, score in zip(names, scores):
    print(f"{name} scored {score}")

⏭️ Coming Up Next: Functions and Reusable Code

Next time we’ll build your own functions, pass in arguments, return results, and organize code better with reusability in mind.

Want a mini quiz or coding challenge before moving on? Just say the word.

Leave a comment