Syntax
Overview of Python Syntax
For-Loops
Iterate Through a List in Reverse Order
We can use the range(start, stop, step)
function to start the iteration from the end of the list. In the example below, we iterate in reverse order to reverse the order of integers in a list.
Iterate Through a List
While-Loops
Iterate Through a Sequence of Floats
Range
The range()
function in Python creates an immutable sequence of integers, which can very helpful for iterating through loops. Note that the stop
is exclusive, meaning it will not be included in the sequence.
Parameters
start
Optional - Integer to specify the start position (defaults to 0).
stop
Required - Integer to specify the stop position.
step
Optional - Integer to specify the sequence increment (defaults to 1).
In the examples below, a for-loop
is used with the range()
function to iterate through a sequence of integers and print each item in the sequence.
Minimal Example
Here, range(4)
creates a sequence of integers from 0 to 4, in increments of 1, but excluding 4.
Comprehensive Examples
Here, range(3, 6)
creates a sequence of integers from 3 to 6, in increments of 1, but excluding 6.
Here, range(4, 20, 4)
creates a sequence of integers from 4 to 20, in increments of 4, but excluding 20.
Enumerate
Parameters
iterable
Required - The iterable to be enumerated (e.g., list, strings, dict, ...).
start
Optional - Integer to specify the start position (defaults to 0).
In the examples below, a for-loop
is used with the enumerate()
function to iterate through a sequence of values and print each index and item from the sequence.
Minimal Example
Here, enumerate(myList)
adds a counter to each item in the list, starting at 0.
Comprehensive Example
Here, enumerate(myList, 2)
adds a counter to each item in the list, starting at 2.
Last updated
Was this helpful?