DEV Community

MercyMburu
MercyMburu

Posted on

Mastering Python iteration: Loops and the magic of list comprehensions

An image illustrating loops in python

What are loops?


They can be termed simply as a way to repeatedly execute some code➿.

For example:

planets= ['mercury','venus','earth','mars','jupyter','saturn','uranus','neptune']
for planet in planets:
print(planet,end='')

# The end='' overrides the \n behavior and instead adds a space ('') after each planet name

output: Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune 
Enter fullscreen mode Exit fullscreen mode

The for loop specifies:

The variable names to use in this case, ‘planet’
The set of values to loop over ‘planets’
You use the word ‘in’ to link them together.

NB :The object right to the ‘in’ can be thought of as a set of a group of things you can probably loop over.

We can also iterate over elements in a tuple. Difference between lists and tuples is that tuple elements are put inside parenthesis and they are immutable i.e. cannot be assigned new values to them once assigned.

multiplicands=(2,2,2,3,3,5)
product = 1
for mult in multiplicands:
product=product*mult

product

Output:360
Enter fullscreen mode Exit fullscreen mode

Multiplicands holds the values to be multiplied together. The ‘product=1’ initializes the variable product that will be used to store the final multiplication answer. ‘for mult in multiplicands’ is a for loop that iterates over each number represented by variable ‘mult’ in the multiplicands tuple.
‘product = product * mult’ is a line executed for each iteration on the loop.

  • Retrieves the current value of the product variable.
  • Multiplies it with the current mult value from the tuple.
  • Assigns the result back to the product variable, updating it with the new product.
  • The code effectively multiplies together all the numbers in the multiplicands tuple, resulting in 2 x 2 x 2 x 3 x 3 x 5 = 360. You can even loop through each character in a string:
s = 'steganograpHy is the practicE of conceaLing a file, message, image, or video within another fiLe, message, image, Or video.'
msg = ''
# print all the uppercase letters in s, one at a time

for char in s:
if char.isupper():
print(char)

output: HELLO
Enter fullscreen mode Exit fullscreen mode

Range()
A function that returns a sequence of numbers and is very useful in writing loops. For instance, if we want to repeat some action 5 times:

for i in range(5):
print('Doing important work.i=',i)
Output:
Doing important work. i = 0
Doing important work. i = 1
Doing important work. i = 2
Doing important work. i = 3
Doing important work. i = 4
Enter fullscreen mode Exit fullscreen mode

In this case the loop variable is named i and range(5) generates a sequence of numbers from 0 to 5.In each iteration, the value of i is inserted into the string using string formatting. So the printing is done 5 times equivalent to the sequence range.

While loops
Iterate until some condition is met.

i=0
while i<10:
print(i)
i+= 1 #increase the value of i by 1
output: 0 1 2 3 4 5 6 7 8 9 
Enter fullscreen mode Exit fullscreen mode

List Comprehensions
Are one of python’s most beloved features. The easiest way of understanding them is to probably look at examples.

squares= [n**2 for n in range(10)]
squares

Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Enter fullscreen mode Exit fullscreen mode

Here’s how we would do the same thing without a list comprehension:

squares=[]
for n in range(10):
squares.append(n**2)
squares

Output:[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Enter fullscreen mode Exit fullscreen mode

We can also add an ‘if’ condition

short_planets = [planet for planet in planets if len(planet) < 6]
short_planets

Output: ['Venus', 'Earth', 'Mars']
Enter fullscreen mode Exit fullscreen mode

(If you’re familiar with SQL, you might think of this as being like a “WHERE” clause)

Here’s an example for filtering with an ‘if’ condition and applying some transformations to the loop variable:

# str.upper() returns all-caps version of a string
loud_short_planets=[planet.upper() + '!' for planet in planets if len(planet)<6]
loud_short_planets

Output:['VENUS!', 'EARTH!', 'MARS!']
Enter fullscreen mode Exit fullscreen mode

People usually write these on a single line, but you might find the structure clearer when split into 3 lines:

[
planet.upper()+'!'
for planet in planets
if len(planet)<6
]
Output: ['VENUS!', 'EARTH!', 'MARS!']
Enter fullscreen mode Exit fullscreen mode

Continuing in the SQL analogy, you could think of these 3 lines as SELECT, FROM and WHERE.

List comprehensions combined with functions like min, max and sum can lead to impressive one-line solutions for problems that would otherwise require several lines of code.

For example compare the following two cells of code that do the same thing:

def count_negatives(nums):
"""Return the number of negative numbers in the given list.
>>> count_negatives([5, -1, -2, 0, 3])
    2
    """
n_negative=0
for num in nums:
if num<0:
n_negative=n_negative + 1
return n_negative
Enter fullscreen mode Exit fullscreen mode

Here is a code using list comprehension instead:

def count_negatives(nums):
return len([num for num in nums if num<0])
Enter fullscreen mode Exit fullscreen mode

Much better right? Especially in terms of lines of code.

Solving a problem with less code is always nice, but it’s worth keeping in mind the following lines from The Zen of Python:

Readability counts
Explicit is better than implicit
So use tools that make compact readable programs. But when you have to choose, favor code that is easy for others to understand.

A special thanks to the Kaggle community for their contributions to open-source data and code. This article benefitted greatly from the resources available on their platform: https://www.kaggle.com/.

Thank you!💌

Top comments (0)