It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

Combining Lists and Functions

What You’ll Learn

In this lesson, you’ll learn how to process a list of items using a function. This is useful when you want to perform the same action for each item in a list.


Functions + Lists = Power

Let’s say we want to greet a bunch of students using our greet_user() function from earlier. Instead of calling the function one by one, we can loop through a list and use the function.

def greet_user(name):
    print("Hi", name + "!")
    print("Welcome to LanceCourse!")

students = ["Ama", "Kofi", "Abena", "Yaw", "Afia"]

for student in students:
    greet_user(student)

This prints a welcome message for each student in the list. Clean, readable, and powerful.

Custom Example

Let’s build a function that checks the length of words in a list and prints a comment.

def check_word_length(word):
    if len(word) > 5:
        print(f"{word} is a long word.")
    else:
        print(f"{word} is a short word.")

words = ["banana", "cat", "elephant", "sky"]

for w in words:
    check_word_length(w)

Real-World Use Case

Imagine you’re analyzing user comments and want to print whether each comment is positive, negative, or neutral. You can write a function for that and use it inside a loop to process a whole list of comments.

Bonus Tip

Functions help you break complex tasks into simple chunks. Combining them with lists allows you to work with data efficiently, especially when you don't know how many items are coming in.

Exercise: Try It Yourself!

  1. Write a function called square(num) that prints the square of a number. Then use it to process this list: [1, 2, 3, 4, 5]

  2. Write a function is_even(n) that checks whether a number is even or odd, and prints the result. Use it to loop through [10, 15, 20, 25].

  3. Create a list of product names. Write a function announce(product) that prints: “Now selling: <product>!” and use it to announce all products in your list.

Summary

  • You can use functions inside loops to process lists.
  • This helps you perform repetitive tasks more efficiently.
  • Reusability = less code, fewer errors.