Python course at https://codecademy.com
Python data structures tutorial https://docs.python.org/2/tutorial/datastructures.html
Python lists are used to store a collection of data. For example, a collection of integers:
x = [1, 2, 6, 4]
x
[1, 2, 6, 4]
Or a collection of floating point numbers:
x = [1.1, 3.0]
x
[1.1, 3.0]
Or even heterogeneous data, like an integer and a floating point number and a string:
x = [1, 1.3, 'string']
x
[1, 1.3, 'string']
You can even have list of lists, and those can be heterogeneous as well
x = [['a list', 'of strings'],[1,2,3]]
x
[['a list', 'of strings'], [1, 2, 3]]
Lists support indexing to extract the data stored in them.
x[0][1]
'of strings'
You can also perform operations on lists, e.g. appending values
x = [1,2,3]
x.append(4)
x
[1, 2, 3, 4]
Or inserting into the middle of them.
x.insert(2, 10)
x
[1, 2, 10, 3, 4]
Or sorting
x.sort()
x
[1, 2, 3, 4, 10]
There is a shorthand syntax for appending lists to other lists
x = [['a list', 'of strings'],[1,2,3]]
x + [[1.1, 2.2]]
[['a list', 'of strings'], [1, 2, 3], [1.1, 2.2]]
You can also use the indexing syntax for reassignment. For example, to replace the first positing of the list x
, you can use the O
th index. In Python, counting starts from 0
.
x[0] = ['another list']
x
[['another list'], [1, 2, 3]]
Lists are mutable! Meaning they can be changed, extended, appended, inserted into, sorted, etc.
Tuples are kind of like constant list. If you have data that you want to store in a structure, but you know it will not be changed, tuples can be more efficient. The syntax for tuples is given in the example below:
x = (1, 2, 3)
There is an effiecent "unpacking" syntax for tuples.
a, b, c = x
a
1
b
2
c
3
You cannot reassign values in a tuple. They are immutable!
x[0] = 4
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-16-cf11c33f17a7> in <module>() ----> 1 x[0] = 4 TypeError: 'tuple' object does not support item assignment
Dictionaries are a way to efficient store and retrieve keyword: value
type data. For example:
my_dict = {'numerical' : 1, 'alphabetical': 'abc'}
Then we can look up the value of 'numerical'
quickly:
my_dict['numerical']
1
Or 'alphabetical'
my_dict['alphabetical']
'abc'
Just likes lists, you can have a dictionary-of-dictionaries
my_dict = {'numerical' : {'linear solver' : 'gmres'}, 'alphabetical': 'abc'}
To return the value of 'linear solver'
directly
my_dict['numerical']['linear solver']
'gmres'