Exercise: Lists and Loops

Exercise 1: Printing Elements of a List

Task: Create a list of 5 of your favorite movies and write a loop to print each movie.

Instructions:

  • Create a list named movies with 5 movie titles.
  • Write a for loop that iterates over the list and prints each movie.
Show solution
movies = ["Inception", "The Matrix", "Interstellar", "The Shawshank Redemption", "The Godfather"]
for movie in movies:
    print(movie)
Inception
The Matrix
Interstellar
The Shawshank Redemption
The Godfather

Exercise 2: Summing Numbers in a List

Task: Create a list of numbers and write a loop to calculate and print the sum of all numbers in the list.

Instructions:

  • Create a list named numbers with at least 5 integer values.
  • Use a loop to iterate over the list and calculate the sum.
  • Print the sum after the loop completes.
Show solution
numbers = [10, 20, 30, 40, 50]
total_sum = 0
for num in numbers:
    total_sum += num # Or: total_sum = total_sum + num

print("The total sum is:", total_sum)  # Output: The total sum is: 150
The total sum is: 150

Exercise 3: Counting Number of Characters in a List of Words

Task: Create a list of words and write a loop to count how many characters (i.e., letters) the list contains in total. Print the count.

Instructions:

  • Create a list named words with several words.
  • Write a loop to iterate through the list and count the letters of each word using the function len(). Sum the count.
  • Print the count.
Show solution
words = ["Python", "code", "Python", "learning", "tutorial", "Python"]
count = 0
for word in words:
    count += len(word)

print(f"The list contains a total of {count} characters.")
The list contains a total of 38 characters.

Exercise 4: Doubling Elements of a List

Task: Create a loop that doubles each number in a list and prints the new list.

Instructions:

  • Create a list named numbers with some integer values.
  • Use a loop to create a new list doubled_numbers where each element is double the corresponding element in numbers.
  • Print the new list.
Show solution
numbers = [1, 3, 5, 7, 9]
doubled_numbers = []
for num in numbers:
    doubled_numbers.append(num * 2)

print(doubled_numbers)  # Output: [2, 6, 10, 14, 18]
[2, 6, 10, 14, 18]

Exercise 5: Count Vowels in a List of Words

Task: Write a function that counts the total number of vowels in a list of words.

Instructions:

  • Define a function called count_vowels(word_list) that takes a list of strings word_list.
  • Inside the function, loop through each word in the list, count the vowels (a, e, i, o, u) in each word, and keep a running total.
  • Return the total count of vowels.
  • Call the function with a sample list (e.g., ["NLP", "is", "fun"]) and print the result.
Show solution
def count_vowels(word_list):
    vowels = 'aeiouAEIOU'
    total_vowels = 0

    for word in word_list:
        for char in word:
            if char in vowels:
                total_vowels += 1
                
    return total_vowels

# Sample usage
words = ["NLP", "is", "fun"]
result = count_vowels(words)
print("Total number of vowels:", result)  
Total number of vowels: 2

Exercise 6: Filter Long Words

Task: Create a function that filters out words longer than a specified length from a list.

Instructions:

  • Define a function called filter_long_words(word_list, length) that takes a list of strings word_list and an integer length.
  • Inside the function, use a loop to create a new list that contains only the words from the original list that have a length less than or equal to length.
  • Return the new list.
  • Call the function with a sample list and a length (e.g., ["Natural", "Language", "Processing", "is", "fun"], length=4) and print the result.
Show solution
def filter_long_words(word_list, length):
    short_words = []
    
    for word in word_list:
        if len(word) <= length:
            short_words.append(word)
    
    return short_words

# Sample usage
words = ["Natural", "Language", "Processing", "is", "fun"]
result = filter_long_words(words, 4)
print("Filtered words:", result)  
Filtered words: ['is', 'fun']

Exercise 7: Create a Word Frequency Dictionary

Task: Write a function that creates a frequency dictionary from a list of words.

Instructions:

  • Define a function called word_frequency(word_list) that takes a list of strings word_list.
  • Inside the function, use a loop to create a dictionary where the keys are the words and the values are the number of times each word appears in the list.
  • Return the frequency dictionary.
  • Call the function with a sample list (e.g., ["NLP", "is", "fun", "NLP"]) and print the result.
Show solution
def word_frequency(word_list):
    frequency_dict = {}

    for word in word_list:
        if word in frequency_dict:
            frequency_dict[word] += 1
        else:
            frequency_dict[word] = 1
            
    return frequency_dict

# Sample usage
words = ["NLP", "is", "fun", "NLP"]
result = word_frequency(words)
print("Word frequency:", result)  
Word frequency: {'NLP': 2, 'is': 1, 'fun': 1}

Exercise 8: Reverse Each Word in a List

Task: Create a function that reverses each word in a list.

Instructions:

  • Define a function called reverse_words(word_list) that takes a list of strings word_list.
  • Inside the function, use a loop to create a new list that contains each word reversed.
  • Return the new list.
  • Call the function with a sample list (e.g., ["NLP", "is", "fun"]) and print the result.
Show solution
def reverse_words(word_list):
    reversed_list = []
    
    for word in word_list:
        reversed_list.append(word[::-1])
    
    return reversed_list

# Sample usage
words = ["NLP", "is", "fun"]
result = reverse_words(words)
print("Reversed words:", result) 
Reversed words: ['PLN', 'si', 'nuf']
Back to top