Techno Blender
Digitally Yours.

Python Loops: A Complete Guide On How To Iterate in Python | by Federico Trotta | Sep, 2022

0 65


Leveraging the power of loops in Python

Photo by 愚木混株 cdd20 on Unsplash

Some months ago, I wrote an article on loops and statements in Python; this article was related to making you understand loops and statements.

Instead, in this article, I want to cover in more depth some different possibilities of using loops, with some exercises.

The first thing I want to show you is list comprehension, and why and when to use it. First, I advise you to read my previous article on loops and statements because you need a deep understanding of these topics.

We use list comprehension when we want to create new lists based on values already existing in a list. Let’s make an example.

Consider we have a list of 10 numbers:

#creating alist of 10 numbers
a = list(range(10))

We want two create two new lists:

  • one with values minor than 3
  • another with values greater than 3

With the classical approach, we have to write a for cycle which iterates over the list “a” and appends the values minor than 3 in a new list and the values greater than 3 in another new list; the following code does this:

#creating a list of 10 numbers
a = list(range(10))
#creating two new and empty new lists
y_1, y_2 = [], []
#creating the cycle
for y in a:
if y>3:
y_1.append(y)
else:
y_2.append(y)
#printing the new lists
print(y_1)
print(y_2)
>>> [4, 5, 6, 7, 8, 9]
[0, 1, 2, 3]

Using the list comprehension method we can simply declare a new list in one line of code; just like that:

#creating a list of 10 numbers
a = list(range(10))
#creating a new list with a condition
c = [x for x in a if x>3]
#creating another new list with a condition
d = [x for x in a if x<=3]
#printing the new lists
print(c)
print(d)
>>>

[4, 5, 6, 7, 8, 9]
[0, 1, 2, 3]

I believe this example shows very well how easy is to use list comprehension when we want to create new lists based on an existing one. Now, think of a situation when you might have more than two conditions; you may want to create, for example, 5 lists based on an existing one…you can really understand how much time and code you save using list comprehension rather than a classical for cycle with ‘if’, ‘elif, ‘else’.

Sorry, but now I realize I haven’t introduced yet the ‘elif’ construct. Let’s see it very quickly:

#creating a list in a range
a = list(range(30))
#creating 3 empty lists
y_1, y_2, y_3 = [], [], []
#creating the cycle
for y in a:
if y>=0 and y<10:
y_1.append(y)
elif y>=10 and y<20:
y_2.append(y)
else:
y_3.append(y)
#printing the lists
print(y_1)
print(y_2)
print(y_3)
>>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

So, the ‘elif’ construct allows us to get the data after the first ‘if’ construct.

A dictionary is a very useful “data container” because each element has a “key” and a “value”. For example, consider we want to store the price of some houses. We can create a dictionary like that:

#my dictionary
house_prices = {'house_1':100000, 'house_2':250000, 'house_3':125000}

Here, the ‘key’ is the string part and the ‘value’ is the number. In these cases we can, for example, iterate through the keys or the values. For example, suppose we want to print all the values we can do it like so:

#accessing ant printing the values
for values in house_prices.values():
print(values)
>>> 100000
250000
125000

Please, note that in a dictionary the ‘values’ can even be strings. For example, suppose we want to store the names and surnames of some people; then, we want to save the names in a list and print the list:

#creating the dictionary
people = {'Jhon':'Doe', 'Mick':'Brown', 'James':'White'}
#creaitng an empty list
my_list = []
#accessing the values and appending to the list
for keys in people:
my_list.append(keys)
#printing the list
print(f'people names are:{my_list}')
>>>
people names are:['Jhon', 'Mick', 'James']

Would you guess how to simplify this notation? Oh, yes! Using list comprehension!

names = [name for name in people]print(names)>>>  ['Jhon', 'Mick', 'James']

And, of course, the same for the values of the dictionary:

surnames = [surname for surname in people.values()]print(surnames)>>>  ['Doe', 'Brown', 'White']

Now, with dictionaries, we can create a lot of beautiful records. Suppose we have recorded data of some houses and we know the coordinate of the house, the extension, the price, and if it has some land. We can store all these data in dictionaries and we can create a list from them, like so:

#creating an empty list
estates = []
#storing the house data and appending to the list
e1 = {'coordinates':[12.3456, -56.7890], 'extension':2000, 'has_land':False, 'price':10}
estates += [e1] #appending to the list#storing the house data and appending to the list
e2 = {'coordinates':[-8.9101, 60.1234], 'extension':12000, 'has_land':False, 'price':125}
estates += [e2] #appending to the list#storing the house data and appending to the list
e3 = {'coordinates':[45.6789, 10.3456], 'extension':100, 'has_land':True, 'price':350}
estates += [e3] #appending to the list

Now, after we’ve appended the dictionaries to the list ‘estates’ we can iterate through it and print the information like that:

for i, e in enumerate(estates):
print(f'\nHouse #:{i}')
print(f"Coordinates: {e['coordinates']}")
print(f"Extension (mq): {e['extension']}")
print(f"Has land?:{'Yes' if e['has_land']==True else 'No'}")
print(f"Price: {e['price']}K $")
>>> House #:0
Coordinates: [12.3456, -56.789]
Extension (mq): 2000
Has land?:No
Price: 10K $

House #:1
Coordinates: [-8.9101, 60.1234]
Extension (mq): 12000
Has land?:No
Price: 125K $

House #:2
Coordinates: [45.6789, 10.3456]
Extension (mq): 100
Has land?:Yes
Price: 350K $

Please, note that you could not write print(f'Coordinates:{e['coordinates']}') otherwise an f-string:unmatched '[' an error will raise. This is due to the fact that, in this case, I’ve used a single ‘ ‘ both after the “f” and in “coordinates”. If you use a double “” after the “f” like in the above code, you won’t have any problem (please: refer to this discussion on Stack Over Flow).

I find that while cycles are easy to understand, but may be difficult to see their real use.

As the word suggests, a while cycle works…while a certain condition is met. A typical example of an exercise is something like that:

print i as long as i is less than 6

We can do it what the following code:

i = 1
while i < 6:
print(i)
i += 1
>> 1
2
3
4
5
6

I think that this example may be a little confusing because we set “i” equal to 1 and so one can say: “well, while “i<6” is obvious since we set i=6; so, what’s the point?”

While loops are very useful when we have a condition that dynamically changes, for example over time, and I believe that it can be better understood with a practical example.

Consider for example the website “worldometers”. This website collects world statistics in real-time.

Let’s imagine you want to get data about the world population; so you write a bot that gets this data. Analysts say that very soon the world population will reach the value of 8 billion; so, your bot can have awhile cycle with a threshold of 8 billion; while the world population is minor than the threshold, we can pass it; when the population reaches 8 billion we can print(f'we are 8 billions in the world!!')

I hope I gave you a good guide on a deep understanding of loops in some different cases. Now it’s your time to do some exercises and mini-projects on loops!


Leveraging the power of loops in Python

Photo by 愚木混株 cdd20 on Unsplash

Some months ago, I wrote an article on loops and statements in Python; this article was related to making you understand loops and statements.

Instead, in this article, I want to cover in more depth some different possibilities of using loops, with some exercises.

The first thing I want to show you is list comprehension, and why and when to use it. First, I advise you to read my previous article on loops and statements because you need a deep understanding of these topics.

We use list comprehension when we want to create new lists based on values already existing in a list. Let’s make an example.

Consider we have a list of 10 numbers:

#creating alist of 10 numbers
a = list(range(10))

We want two create two new lists:

  • one with values minor than 3
  • another with values greater than 3

With the classical approach, we have to write a for cycle which iterates over the list “a” and appends the values minor than 3 in a new list and the values greater than 3 in another new list; the following code does this:

#creating a list of 10 numbers
a = list(range(10))
#creating two new and empty new lists
y_1, y_2 = [], []
#creating the cycle
for y in a:
if y>3:
y_1.append(y)
else:
y_2.append(y)
#printing the new lists
print(y_1)
print(y_2)
>>> [4, 5, 6, 7, 8, 9]
[0, 1, 2, 3]

Using the list comprehension method we can simply declare a new list in one line of code; just like that:

#creating a list of 10 numbers
a = list(range(10))
#creating a new list with a condition
c = [x for x in a if x>3]
#creating another new list with a condition
d = [x for x in a if x<=3]
#printing the new lists
print(c)
print(d)
>>>

[4, 5, 6, 7, 8, 9]
[0, 1, 2, 3]

I believe this example shows very well how easy is to use list comprehension when we want to create new lists based on an existing one. Now, think of a situation when you might have more than two conditions; you may want to create, for example, 5 lists based on an existing one…you can really understand how much time and code you save using list comprehension rather than a classical for cycle with ‘if’, ‘elif, ‘else’.

Sorry, but now I realize I haven’t introduced yet the ‘elif’ construct. Let’s see it very quickly:

#creating a list in a range
a = list(range(30))
#creating 3 empty lists
y_1, y_2, y_3 = [], [], []
#creating the cycle
for y in a:
if y>=0 and y<10:
y_1.append(y)
elif y>=10 and y<20:
y_2.append(y)
else:
y_3.append(y)
#printing the lists
print(y_1)
print(y_2)
print(y_3)
>>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

So, the ‘elif’ construct allows us to get the data after the first ‘if’ construct.

A dictionary is a very useful “data container” because each element has a “key” and a “value”. For example, consider we want to store the price of some houses. We can create a dictionary like that:

#my dictionary
house_prices = {'house_1':100000, 'house_2':250000, 'house_3':125000}

Here, the ‘key’ is the string part and the ‘value’ is the number. In these cases we can, for example, iterate through the keys or the values. For example, suppose we want to print all the values we can do it like so:

#accessing ant printing the values
for values in house_prices.values():
print(values)
>>> 100000
250000
125000

Please, note that in a dictionary the ‘values’ can even be strings. For example, suppose we want to store the names and surnames of some people; then, we want to save the names in a list and print the list:

#creating the dictionary
people = {'Jhon':'Doe', 'Mick':'Brown', 'James':'White'}
#creaitng an empty list
my_list = []
#accessing the values and appending to the list
for keys in people:
my_list.append(keys)
#printing the list
print(f'people names are:{my_list}')
>>>
people names are:['Jhon', 'Mick', 'James']

Would you guess how to simplify this notation? Oh, yes! Using list comprehension!

names = [name for name in people]print(names)>>>  ['Jhon', 'Mick', 'James']

And, of course, the same for the values of the dictionary:

surnames = [surname for surname in people.values()]print(surnames)>>>  ['Doe', 'Brown', 'White']

Now, with dictionaries, we can create a lot of beautiful records. Suppose we have recorded data of some houses and we know the coordinate of the house, the extension, the price, and if it has some land. We can store all these data in dictionaries and we can create a list from them, like so:

#creating an empty list
estates = []
#storing the house data and appending to the list
e1 = {'coordinates':[12.3456, -56.7890], 'extension':2000, 'has_land':False, 'price':10}
estates += [e1] #appending to the list#storing the house data and appending to the list
e2 = {'coordinates':[-8.9101, 60.1234], 'extension':12000, 'has_land':False, 'price':125}
estates += [e2] #appending to the list#storing the house data and appending to the list
e3 = {'coordinates':[45.6789, 10.3456], 'extension':100, 'has_land':True, 'price':350}
estates += [e3] #appending to the list

Now, after we’ve appended the dictionaries to the list ‘estates’ we can iterate through it and print the information like that:

for i, e in enumerate(estates):
print(f'\nHouse #:{i}')
print(f"Coordinates: {e['coordinates']}")
print(f"Extension (mq): {e['extension']}")
print(f"Has land?:{'Yes' if e['has_land']==True else 'No'}")
print(f"Price: {e['price']}K $")
>>> House #:0
Coordinates: [12.3456, -56.789]
Extension (mq): 2000
Has land?:No
Price: 10K $

House #:1
Coordinates: [-8.9101, 60.1234]
Extension (mq): 12000
Has land?:No
Price: 125K $

House #:2
Coordinates: [45.6789, 10.3456]
Extension (mq): 100
Has land?:Yes
Price: 350K $

Please, note that you could not write print(f'Coordinates:{e['coordinates']}') otherwise an f-string:unmatched '[' an error will raise. This is due to the fact that, in this case, I’ve used a single ‘ ‘ both after the “f” and in “coordinates”. If you use a double “” after the “f” like in the above code, you won’t have any problem (please: refer to this discussion on Stack Over Flow).

I find that while cycles are easy to understand, but may be difficult to see their real use.

As the word suggests, a while cycle works…while a certain condition is met. A typical example of an exercise is something like that:

print i as long as i is less than 6

We can do it what the following code:

i = 1
while i < 6:
print(i)
i += 1
>> 1
2
3
4
5
6

I think that this example may be a little confusing because we set “i” equal to 1 and so one can say: “well, while “i<6” is obvious since we set i=6; so, what’s the point?”

While loops are very useful when we have a condition that dynamically changes, for example over time, and I believe that it can be better understood with a practical example.

Consider for example the website “worldometers”. This website collects world statistics in real-time.

Let’s imagine you want to get data about the world population; so you write a bot that gets this data. Analysts say that very soon the world population will reach the value of 8 billion; so, your bot can have awhile cycle with a threshold of 8 billion; while the world population is minor than the threshold, we can pass it; when the population reaches 8 billion we can print(f'we are 8 billions in the world!!')

I hope I gave you a good guide on a deep understanding of loops in some different cases. Now it’s your time to do some exercises and mini-projects on loops!

FOLLOW US ON GOOGLE NEWS

Read original article here

Denial of responsibility! Techno Blender is an automatic aggregator of the all world’s media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – [email protected]. The content will be deleted within 24 hours.
Leave a comment