Lists
Traversing a list
Print each element of a list.
Traversing a list means visiting every element in turn. There are several ways:
- for item in nums: print(item) visits each element from the first to the last. It is the simplest way when you just need the values.
- for i in range(len(nums)): print(nums[i]) loops over the indices 0, 1, 2 … len(nums) - 1. Use it when you need the position, or want to change elements.
- A while loop with a counter does the same: i = 0; while i < len(nums): print(nums[i]); i += 1.
To change each element during traversal, use the index form: for i in range(len(nums)): nums[i] = nums[i] + 5. (In the simple for item in nums form, item is only a copy of the value, so changing item does not change the list.)
Traversal is the basis of most list tasks: searching for an element, counting, summing, and building new lists.
for item in list, or for i in range(len(list)).
Practise this lesson
Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.
No account, no email address. Opens the real product.