Skip to content

Instantly share code, notes, and snippets.

@JimHokanson
Last active March 1, 2016 22:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JimHokanson/a3c8b3eac0e86245c17a to your computer and use it in GitHub Desktop.
Save JimHokanson/a3c8b3eac0e86245c17a to your computer and use it in GitHub Desktop.
Transititioning from Matlab to Python

Transitioning to Python from Matlab

Indexing vs Calling

In Matlab, there is not distinction between indexing and calling. Both are accomplished with parentheses.

a = 1:5
b = a(2:3) %indexing
c = sum(a) %calling

In Python, these are different things, and indexing is indicated by brackets []

a = [1,2,3,4,5]
b = a[1:3] #This is an indexing operation []
c = sum(a) #This is a calling operation ()

If we forget this, we get an error that something is not callable

>>> b = a(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable

A similar error is if something is not subscriptable, which occurs when we try to index with a method. I find this often occurs when I forget to call a method previously. This is another importance difference between Matlab and Python.

In Matlab, to work with a function as a variable requires a function handle:

s = @sum
c = s(1:5)

In Python, working with a function (or class) as a variable requires omitting the parentheses

s = sum
c = s([1,2,3,4,5])

This issue will most often arise when no input arguments are required. For example, one way of debugging is the following.

import pdb
pdb.set_trace()

Note, if we instead do the following, then nothing will happen because set_trace is not being called.

import pdb
pdb.set_trace #missing ()

Python lists

Unlike Matlab, manual initialization of a list in Python requires commas:

>>> my_list = [1,2,3,4]
>>> my_list = [1 2 3 4]
  File "<stdin>", line 1
    my_list = [1 2 3 4]
                 ^
SyntaxError: invalid syntax

Installation

I prefer to use conda to manage package installation where possible.

pip

pip works ok as long as you are calling the right pip. If you have multiple Pyhton installations the pip function that gets resolved by the OS might not belong to the Python installation that you are using. When using conda I prefer to do the following in Windows:

C:\Users\Jim>conda info
root environment : C\Users\Jim\Anaconda3

C:\Users\Jim>cd "C:\Users\Jim\Anaconda3\Scripts"

pip install selenium ::We're now running the pip that is local

TODO: List comprehension

@JimHokanson
Copy link
Author

TODO: Should mention returning None and forgetting to return something

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment