Python
{'star wars episode V': 1980, 'the godfather': 1972, 'the dark knight': 2008}
than what I could cover in Just Enough Python
2022-11-22
This tutorial is under construction.
I wish I had time to cover everything in-depth, but then I’d have to change the title from “Just Enough Python” to “Way More Python Than We Could Possibly Cover In An Hour”. So as a compromise, here’s just a little more Python.
Python
{'star wars episode V': 1980, 'the godfather': 1972, 'the dark knight': 2008}
Use a set instead of a list when order doesn’t matter and you want every item to be unique.
Python
{'John', 'George', 'James', 'Thomas'}
Looking up whether a set contains an item is more efficient than using a list.
Using packages works a little differently between R and Python.
In R, you can refer to a function from any package you have installed with double colons:
Alternatively, you can first load the package at the top of your script so you can call the functions you want to use without specifying the package name every time you use them.
In Python, you must import
a package before you can use anything from it and reference the package name like this:
You can give a package a nickname to cut down on the characters you have to type. pandas
is often renamed to pd
:
Alternatively, you can choose to import only the functions you want to use from a package:
I wish I had enough time to cover object-oriented programming (OOP) in depth, but we’re only going to scratch the surface.
Everything in Python is an object. This is also true in R. You can find out what class an object belongs to in Python with type()
:
<class 'list'>
<class 'str'>
True
or in R with class()
:
[1] "integer"
[1] "list"
[1] "character"
[1] TRUE
Lists have methods that can modify them in place
[1, 2, 3, 4]
[5, 4, 3, 2, 1]
You can split a string into a list based on a separator character with split()
:
['path/to/file', 'txt']
'path/to/file'
Use join()
to do the opposite of split()
:
'patient_id,sample_id,collection_date'
You can even define your own classes! Use the class
keyword and define __init__
– the function that initializes a new instance of the class.
name
is an attribute of the Dog class. is_good()
is a method of the Dog class. Create a new instance of the Dog
class and try using it:
TODO explain how this works in Snakemake input/output/params etc
Take advantage of object-oriented programming to DRY your code by referencing output files from other rules.