Lesson 15 of 55
9 mins readPython Foreach Loops & The Default Variable ($_)
In Plain English
`foreach` (synonymous with `for` in Perl) iterates over lists. When no loop variable is named, Perl assigns each item to the default topic variable `$_`.
Deep Dive: How It Works
for and foreach: Completely interchangeable keywords in Perl.
The Default Variable ($_): Represents the current item during iteration.
Aliasing: Modifying the loop variable directly modifies the original list elements in-place.
Core Rules to Remember

List Iteration: `foreach my $item (@list)` cleanly inspects every element.

Topic Variable ($_): `print "$_\n" for @list;` is concise and idiomatic.
Live Interactive Example
Hit Run Code to see it liveIterating with Named Variable and $_
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Output Console
Click "Run Code" to view the rendered output.
How it works: Both approaches cleanly iterate through the list.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Iterate with Default Variable
Iterate through the range `(1..4)` using `for (1..4)`.
Print `"Item: $_\n"` inside the loop.
1
2
3
4
5
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.