List Comprehensions

List Comprehensions provide an elegant way to create new lists.
The following shows the basic structure of a list comprehension:
[11]:
[x for x in [1, 2, 3, 4]]
[11]:
[1, 2, 3, 4]

Et for loop der skrives som dette:

[12]:
l = []
for i in range(1, 10):
    l.append(i)
l
[12]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Kunne skrives mere elegangt med en list comprehension

[13]:
[i for i in range(1, 10)]
[13]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

STUDENTS 10 MINUTES TASK

(Ex 1: Alphabet List Comprehensions)

  1. Create a list of capital letters in the english alphabet

  2. Create a list of capital letter from the english aplhabet, but exclude 4 with the Unicode code point of either 70, 75, 80, 85.

  3. Create a list of capital letter from from the english aplhabet, but exclude every second between F & O

if, else

if

[14]:
[x for x in range(1, 10) if x%2 == 0]
[14]:
[2, 4, 6, 8]

else

[15]:
[x  if x%2 == 0 else 'un-even'  for x in range(1, 10)]
[15]:
['un-even', 2, 'un-even', 4, 'un-even', 6, 'un-even', 8, 'un-even']

Nested for loops

Like you can do a nested for loop

[16]:
l = []
for i in range(3):
    for j in range(2):
        l.append((i, j))
l
[16]:
[(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]

You can create nested list comprehensions

[17]:
[(i,j) for i in range(3) for j in range(2)]
[17]:
[(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]

STUDENTS 10 MINUTES TASK

Ex 2: Clothes List Comprehension

  1. From 2 lists, using a list comprehension, create a list containing:

[20]:
[('Black', 's'), ('Black', 'm'), ('Black', 'l'), ('Black', 'xl'), ('White', 's'), ('White', 'm'), ('White', 'l'), ('White', 'xl')]
[20]:
[('Black', 's'),
 ('Black', 'm'),
 ('Black', 'l'),
 ('Black', 'xl'),
 ('White', 's'),
 ('White', 'm'),
 ('White', 'l'),
 ('White', 'xl')]
[21]:
colors = ['Black', 'White']
sizes = ['s', 'm', 'l', 'xl']
  1. If the tuple pair is in the following list, it should not be added to the comprehension generated list.

[ ]:
sold_out = [('Black', 's'),('White', 'l')]

Modules

Build in Modules

The import statement

[25]:
import sys
[ ]:
import sys

def greeting(x):
    print(x)

    if len(x) == 2 and x[1] == '-it':
        print('interactive terminal started')
    if len(x) == 3 and x[2] == '--rm':
        print('Will be removed at exit')

greeting(sys.argv)

STUDENTS 10 MINUTES TASK

Ex 4: Sys module exercise

Create a commandline tool that checks if the required aguments are present when you run the program, and if not tells you what is missing to run the program.

So if you run python script.py the program should print out an error saying Usage: python script.py [-it]{--rm} where the [] means required and the {} means optional.

OS Module

[44]:
import os
os.listdir()
[44]:
['02_datastructures',
 '01_intro',
 '.DS_Store',
 '07_decorators',
 '05_encapsulation',
 'README.md',
 '08_generators',
 '04_oop',
 '09_decorator',
 '.git',
 '06_datamodel',
 '03_modules']

Other usefull OS methods

[ ]:
os.mkdir('Test')
os.chdir('Test')
os.rmdir('Test')

# More: https://realpython.com/working-with-files-in-python/ and https://docs.python.org/3/library/os.html

STUDENTS 10 MINUTES TASK

Ex 5: OS Module Exercise

Do the following task using the os module

  1. create a folder and name the folder ‘os_exercises.’

  2. In that folder create a file. Name the file ‘exercise.py’

  3. get input from the console and write it to the file.

  4. repeat step 2 and 3 (and append to the file).

  5. read the content of the files and and print it to the console.

Subprocess module

Run unix commands through python

import subprocess
subprocess.run([‘pwd’])
subprocess.run([‘touch’, ‘test.py’])
subprocess.run([‘ls’])
subprocess.run([‘rm’, ‘test.py’])
subprocess.run([‘ls’])
subprocess.run([‘pwd’])

Subprocess module

Run git commands through python

import subprocess
subprocess.run([‘git’, ‘clone’, ‘https://github.com/python-elective-kea/fall2020.git’])

subprocess.run([‘ls’])

Requests module (3rd party)

Have to be installed by:

pip install requests

import requests

ModuleNotFoundError: No module named ‘requests’

pip list

pip install requests

pip list

import requests
res = requests.get(’https://api.github.com’)

res.text

Download Images

import requests

f = requests.get(’https://kea.dk/images/resources/logo-main-black-single.png’, allow_redirects=True)

o = open(‘logo.png’, ‘wb’)
o.write(f.content)
[ ]: