library(reticulate)
use_python("/Users/chammika/miniconda3/envs/science-work/bin/python", required = TRUE)Loops (Nice)
The material in this ‘Nice’ chapter is optional. The discussion typically deals with content beyond what a novice should know. So, please finish all the ‘Need’ and ‘Good’ portions before you go through this chapter.
There is more to list comprehension
-
You can have more than one loop in a list comprehension.
[[a,b] for a in range(5) for b in ['A', 'B', 'C']][[0, 'A'] [0, 'B'] [0, 'C'] [1, 'A'] [1, 'B'] [1, 'C'] [2, 'A'] [2, 'B'] [2, 'C'] [3, 'A'] [3, 'B'] [3, 'C'] [4, 'A'] [4, 'B'] [4, 'C']] -
You can even incorporate a condition!
[[a,b] for a in range(5) for b in ['A', 'B', 'C'] if a % 2 != 0][[1, 'A'] [1, 'B'] [1, 'C'] [3, 'A'] [3, 'B'] [3, 'C']] -
nested_list=[[1, 2, 3], [4, 5, 6, 7]] [y for x in nested_list for y in x] nested_list=[[1, 2, 3], [4, 5, 6, 7]] output =[] for x in nested_list: for y in x: output.append(y)Here is a slightly more complicated use of list comprehension to flatten a list.
[1, 2, 3, 4, 5, 6, 7]This does the same as:
Zipping a dictionary
zip() offers one of the easiest ways to combine two lists into a dictionary:
super_names=["Black Widow", "Iron Man", "Doctor Strange"]
real_names=["Natasha Romanoff", "Tony Stark", "Stephen Strange"]
dict(zip(real_names, super_names)){'Natasha Romanoff': 'Black Widow', 'Tony Stark': 'Iron Man', 'Stephen Strange': 'Doctor Strange'}
In the above dict() is used to recast zip()’s output into a dictionary.
for and while has an else
numbers=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in numbers:
if i < 0: break
else:
print('No negative numbers in the list')The for and while loops in Python come with an optional else statement! The code in the else block is executed only if the loops are completed. The else code-block will not run if you exit the loop prematurely (e.g. by using break).
Shown alongside is a trivial example. You should add a negative number to the list, and re-run the snippet. There will be no message this time.
So, the else statement can be used to distinguish between the loops completing as planned or if there was a break (or return or an exception).
No negative numbers in the list