Python list comprehension continue

Successfully use If-ElseStatements, For Loops and List Comprehensions in Python.

When and How to execute flow control structures for logical, clean and organized Python code.

Susan Maina

Dec 10, 2020·7 min read

Photo by Isabella and Louisa Fischer on Unsplash

Control Flow structures such as if statements and for loops are powerful ways to create logical, clean and well organized code in Python. If Statements test a condition and then do something if the test is True. For Loops do something for a defined number of elements. List comprehensions are a neat python way of creating lists on the fly using a single line of code.

Structure and white space indentation: There are two parts to their structure in Python: one is the parent statement line which defines the statement with if or for keywords and this line must end with a : [colon]. Two is the child statement[s] which contain the code block to be implemented if the condition is true[in the case of if statement] or implemented severally [in the case of for loops]. The child statement[s] must be indented with four white spaces [or a tab space] at the beginning otherwise an IndentationError will be thrown.

parent statement:
child statement or code block indented with 4 spaces

If statements

These statements begin with the if keyword followed by a condition which should evaluate to either True or False, followed by a colon. The code block comes in the second line indented in the beginning with 4 white spaces. This is the code to be implemented if the condition is met.

If condition:
code block

Below is an example. Note that if the condition is False, nothing will be displayed. There is no Error.

if 5 > 1:
print['True, Five is greater than One']
### Results
True, Five is greater than One

If Else

You can include an else statement with a block of code to be implemented if the condition is false.

If condition:
code block
else:
code block

Below is an example of If..else statement.

if 'a' > 'b':
print['True']
else:
print['False, "a" is not greater than "b"']
#Results
False, "a" is not greater than "b"

Ifelifelse

You can check for many other conditions using elif [short for else if]. The final else evaluates only when no other condition is true. Note that else and elif statements are optional and you can have one without the other. The first if statement is a must.

age = 60
if age >= 55:
print["You are a senior"]
elif age < 35:
print["You are a youth"]
else:
print["You are middle aged"]
### Results
You are a senior

For loops

A For Loop introduces the concept of iteration, which is when a process is repeated over several elements such as those in a list.

A For Loop contains a for keyword, an iterable such as a list that contains the elements to loop through, a variable name that will represent each element in the list, and the code block that will be run for every element. The code block is indented with 4 white spaces.

for variable_name in list:
code block

The two examples below show for loops that iterate through a list and prints each element in the list. Note that I have included the print results in the same line to save space. But in practice each element is printed in its own line because the print[] function by default adds a new line at the end of each print.

for name in ['sue', 'joe', 'gee']:
print[name]
for num in [1,2,3,4,5]:
print[num+1]
### Results
sue joe gee
2 3 4 5 6

range[]

This function is used to generate integer lists that can be used in for loops. You can create a list by range[stop], range[start,stop] or range[start, stop, step]. start [optional] defines the first number in the sequence and the default is 0. stop [not optional] defines where the list ends but this number is not included in the list, therefore the last number in the sequence is stop-1. Step [optional] is the increment for each number in the list and the default is 1. For example range[10] creates a list from 0 to 9, range[2,10] creates a list from 2 to 9 and range[1,10,2] creates the list [1,3,5,7,9]. Note that range[] creates integer lists only and will throw a TypeError if you pass it anything other than an integer.

for i in range[5]:
print[i]
for i in range[2, 9]:
print[i]
for i in range[0, 11, 2]:
print[i]
### Results
0 1 2 3 4
2 3 4 5 6 7 8
0 2 4 6 8 10

You can also iterate lists in reversed order using reverse[list]

l = [one,two, 'three]for rev in reversed[l]:
print[rev]
for r in reversed[range[95,101]]:
print[r]
### Results
three two one
100 99 98 97 96 95

Nested control flow

You can nest If statements inside For Loops. For example you can loop through a list to check if the elements meet certain conditions.

ages = [78, 34, 21, 47, 9]for age in ages:
if age >= 55:
print["{} is a senior".format[age]]
elif age < 35:
print["{} is a youth".format[age]]
else:
print["{} is middle aged".format[age]]

You can also have a For Loop inside another For loop. Here, for every element in the first list, we loop through all elements in the second list.

first_names = ['john','sam', 'will']
last_names = ['white', 'smith', 'alexander']
for fname in first_names:
for lname in last_names:
print[fname, lname]
### Results
john white
john smith
john alexander
sam white
sam smith
sam alexander
will white
will smith
will alexander

List Comprehensions

List comprehensions are a way to construct new lists out of existing lists after applying transformations to them.

Every list comprehension has an output [usually but not necessarily transformed] and a for loop, and is surrounded by square brackets. Square brackets are used because we are constructing a list.

[transformed_l for l in list]

To construct a set or tuple, enclose the list comprehension with {} or [] respectively. check out this article for the key differences between lists, sets and tuples in python.

Ultimate Guide to Lists, Tuples, Arrays and Dictionaries For Beginners.

A simple guide to creating, updating and manipulating pythons most popular data structures, and their key differences.

towardsdatascience.com

The first code below multiplies each element in the original list by 2 to create a new list. num*2 is the desired output, followed by the for loop. The second code does not transform the elements and outputs the same list.

print[[num*2 for num in [2,4,6,8,10]]]
print[[num for num in [2,4,6,8,10]]]
### Result
[4, 8, 12, 16, 20]
[2, 4, 6, 8, 10]

Conditional Logic: You can add an If statement at the end to return only items which satisfy a certain condition.

[output for l in list if condition]

For example the code below returns only the numbers in the list that are greater than 2.

[l for l in list if l>2]

This code returns a list of heights greater than 160.

heights = [144, 180, 165, 120, 199]
tall = [h for h in heights if h > 160]
print[tall]
### Results
[180, 165, 199]

You can have Conditional Outputs with if..else in the output part. For example, you can classify the elements in a list by creating a new list that holds what class each element in the original list belongs to. Note that you must have both if and else keywords otherwise a SyntaxError is thrown. elif does not apply here.

[output if condition else output for l in list]

The code below creates a list from 0 to 9 then we define a list comprehension which iterates through the list and outputs either even or odd for every number in the list. We use the modulo [%] operator that returns the remainder of a division. A number is even if the remainder of division by 2 is 0, otherwise the number is odd.

nums = list[range[10]]
num_classes = ['even' if num%2 == 0 else 'odd' for num in nums]
print[num_classes]
### Results
['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']

Functions

We cannot talk about flow control and fail to mention Functions. Functions enable you to create reusable blocks of code. They create modularity [separate code blocks that perform specific functions] in your code and enable your code to stay organized.

Functions start with a def keyword, then a desired function name, parenthesis [], and a colon to end the parent statement. Optional arguments can be provided inside the parenthesis which are just variables you pass into the function. The next line contains the code block indented with 4 white spaces. You can have an optional return statement in the last line of the code block that will be the result[output] of the function.

def name[]:
code block
return value

You call a function by simply typing its name then parenthesis. If the function takes in arguments, provide them inside the parenthesis when calling it.

name[]

The following code defines a function which prints Hi there when called. Not that the code block does not have a return statement.

def hello[]:
print['Hi there']
hello[]
### Results
Hi there

The code below defines a function which takes in an integer value and squares it. Note that it does have a return statement.

def square_number[num]:
return num*num
five_squared = square_number[5]
print[five_squared]
### Results
25

A function must contain a code block. This can be just a return statement, or code that does something. If there is no return statement the function will return None by default.

That is a basic guide to Pythons Control Flow Structures. There is so much more you can do and you will be using these concepts alot in data science. I encourage you to practice, practice, practice. Best of luck!

Video liên quan

Chủ Đề