Code
# We assign variables using `=`
first_name = 'Eshin'
first_name'Eshin'
Site Updates: Slides Week 5, Anonymous feedback form,schedule updates
Eshin Jolly
January 7, 2026
This notebook is designed to teach you the essence of Python building upon your understanding of R. We’ll skip some programming basics (see the quickstart in the assignment repo for that) but add references resources to the course website. We’ve structured this notebook to focus on the key bits of Python that might give you trouble coming from R and how to handle them gracefully.
What happens if you do this?
The most common error message you’ll encounter early on. It just means you mistyped something and Python doesn’t understand it.
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[9], line 2 1 # What happens here? ----> 2 my_number > first_name TypeError: '>' not supported between instances of 'int' and 'str'
Another common message telling you that you’re not providing the expected input to the operation you’re trying. In this case Python has no way to check a number is greater than a string!
int
Python like many programming languages distinguishes between numerical values that do or do not require decimal-point precision. Python will always convert to the highest precision it can for you.
Help on built-in function print in module builtins:
print(*args, sep=' ', end='\n', file=None, flush=False)
Prints the values to a stream, or to sys.stdout by default.
sep
string inserted between values, default a space.
end
string appended after the last value, default a newline.
file
a file-like object (stream); defaults to the current sys.stdout.
flush
whether to forcibly flush the stream.
['Eshin', 'Jolly', 'third_name', 'fourth_name']
Notice how the variables in the list start at 0? That’s because unlike R, Python counts starting from 0 not from 1! This is usually the first major difference to get used to and applies to all Python libraries and tools. For example, the first row of a dataframe is row 0 not row 1.
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[20], line 2 1 # What happens if we try this? ----> 2 my_list[4] IndexError: list index out of range
One the most common error messages is just telling you’re trying to retrieve an item in a position that doesn’t exist. In other words the list has too few items and Python doesn’t know what to do.
['Eshin', 'Jolly', 'third_name']
stop
By default Python slices up-to but not-including the stop value. Notice how the 3rd index ("fourth name") was not included even though we used 3.
['Eshin', 'Jolly', 'third_name']
['Eshin', 'third_name']
['fourth_name', 'third_name', 'Jolly', 'Eshin']
Using list[::-1] is a very common pattern for quickly reversing a list in Python
Greater than 0
Python is often loved for being very readable in part because it doesn’t use {} to surround code-block like R, Javascript and other languages. However, that means you need to carefully indent or de-indent to accomplish the same thing.
Greater than 0
What happens here?
Python will let you know if your spacing is off and where it’s happening. You’ll mostly encounter this when you’re editing code, because VSCode will try to be helpful and automatically indent correctly as you’re writing code.
Eshin
Jolly
third_name
fourth_name
Eshin
Jolly
third_name
fourth_name
Help on class enumerate in module builtins:
class enumerate(object)
| enumerate(iterable, start=0)
|
| Return an enumerate object.
|
| iterable
| an object supporting iteration
|
| The enumerate object yields pairs containing a count (from start, which
| defaults to zero) and a value yielded by the iterable argument.
|
| enumerate is useful for obtaining an indexed list:
| (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __class_getitem__(...)
| See PEP 585
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
Try using help() and the examples above to figure out how to use the enumerate() function to print out each item and its position. If the notebook gives you an error about reusing a variable name (e.g. elem) just call your looping variable something else.
Python makes it easy to write your own functions to create usable blocks of code using the def keyword (not function like in R). Then we just use indentation like before:
'ESHIN'
.
Unlike R, Python is an object-oriented-language which means functions can be attached to objects.
We call these methods but you can intuitively treat them the same.
In the example above, Python doesn’t have an upper() function, but strings have a .upper() method. In your head when you see first_name.upper() just think upper(first_name).
This allows for method-chaining which is Python’s alternative to R’s %>% syntax.
In R we might do: function() %>% function() %>% function()
In Python we’ll often do: object.method().method().method() to achieve the same effect.
['__add__',
'__class__',
'__class_getitem__',
'__contains__',
'__delattr__',
'__delitem__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__getstate__',
'__gt__',
'__hash__',
'__iadd__',
'__imul__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__reversed__',
'__rmul__',
'__setattr__',
'__setitem__',
'__sizeof__',
'__str__',
'__subclasshook__',
'append',
'clear',
'copy',
'count',
'extend',
'index',
'insert',
'pop',
'remove',
'reverse',
'sort']
Notice how .append() didn’t return anything? Some methods cannot be chained because they modify the object in-place
Run the cell below to see how the value of the variable my_list has changed Then run the cell below that to .append() a second time and see what happens
There are 5 items:
['Eshin', 'Jolly', 'third_name', 'fourth_name', 'another_item']
There are 6 items:
['Eshin', 'Jolly', 'third_name', 'fourth_name', 'another_item', 'add_another']
import and as
Whereas in R you might use library(lme4) to import a library and automatically get all it’s functions (e.g. lmer), in Python you have to be more explicit. This is because in Python everything is an object including other libraries, which means you can do accidental things like overwrite a library you imported with a variable: