We use length and iteration methods to count items and go through each item in a list or other collection. This helps us work with groups of things easily.
0
0
Length and iteration methods in Python
Introduction
When you want to know how many items are in a list or string.
When you want to do something with each item in a list, like print or change it.
When you want to check if a collection is empty or not.
When you want to add up or find something from all items in a collection.
When you want to repeat an action a certain number of times.
Syntax
Python
len(collection) for item in collection: # do something with item
len() gives the number of items in a collection like list, string, or tuple.
The for loop goes through each item one by one.
Examples
This prints the number of items in the list
numbers, which is 4.Python
numbers = [1, 2, 3, 4] print(len(numbers))
This prints the number of letters in the word "hello", which is 5.
Python
word = "hello" print(len(word))
This prints each fruit name on its own line by going through the list.
Python
fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)
This repeats the loop 3 times, printing numbers 0, 1, and 2.
Python
for i in range(3): print(i)
Sample Program
This program counts how many items are in the list and prints each item one by one.
Python
items = ["pen", "book", "lamp"] print(f"There are {len(items)} items.") for item in items: print(f"Item: {item}")
OutputSuccess
Important Notes
You can use len() on many types like lists, strings, tuples, and dictionaries.
The for loop works with any collection that can be counted or listed.
Indentation is important in Python to show what is inside the loop.
Summary
len() tells you how many items are in a collection.
for loops let you do something with each item in a collection.
These tools help you handle groups of things easily and clearly.