Iterating Over Elements
Part of the Fundamentals section of Coddy's Python journey — lesson 60 of 77.
Iteration means going through elements one by one in a sequence. With lists, we can access each element systematically using different methods.
The most common way to iterate through a list is using a for loop:
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)Output:
apple
banana
orangeWhen iterating, you can also use the len() function to get the number of elements in a list, or to check the length of individual elements. For example, len(fruits) returns 3, and len("apple") returns 5:
words = ["hi", "hello", "hey", "howdy"]
for word in words:
if len(word) > 3:
print(word)Output:
hello
howdyChallenge
EasyCreate a program that receives a list as input (given), and prints a new list containing only the words longer than 5 characters
Cheat sheet
To iterate through a list in Python, use a for loop:
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)This will access each element in the list one by one.
Use len() to get the number of elements in a list:
fruits = ["apple", "banana", "orange"]
print(len(fruits)) # Output: 3len() is often used with loops to check lengths or control iteration.
Try it yourself
lst = input().split(",")
# Write your code belowThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 48Loops
For LoopWhile LoopBreakContinueRecap - FactorialThe Range FunctionNested LoopRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators9Functions
Declare a FunctionArgumentsReturnRecap - Sigma FunctionRecap - Validation FunctionDefault Values12Iterating Over Sequences
Iterating Over ElementsThe Enumerate FunctionIterating Over Strings Part 1Iterating Over Strings Part 2