#!/usr/bin/env python # coding: utf-8 # # Lists, Tuples, and Dictionaries # # ### Other resources # # Python course at https://codecademy.com # # Python data structures tutorial https://docs.python.org/2/tutorial/datastructures.html # ## Lists # # Python lists are used to store a collection of data. For example, a collection of integers: # In[1]: x = [1, 2, 6, 4] x # Or a collection of floating point numbers: # In[2]: x = [1.1, 3.0] x # Or even heterogeneous data, like an integer and a floating point number and a string: # In[3]: x = [1, 1.3, 'string'] x # You can even have list of lists, and those can be heterogeneous as well # In[4]: x = [['a list', 'of strings'],[1,2,3]] x # Lists support indexing to extract the data stored in them. # In[5]: x[0][1] # You can also perform operations on lists, e.g. appending values # In[6]: x = [1,2,3] x.append(4) x # Or inserting into the middle of them. # In[7]: x.insert(2, 10) x # Or sorting # In[8]: x.sort() x # There is a shorthand syntax for appending lists to other lists # In[9]: x = [['a list', 'of strings'],[1,2,3]] # In[10]: x + [[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`. # In[11]: x[0] = ['another list'] x # Lists are mutable! Meaning they can be changed, extended, appended, inserted into, sorted, etc. # ## Tuple # # 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: # In[12]: x = (1, 2, 3) # There is an effiecent "unpacking" syntax for tuples. # In[13]: a, b, c = x a # In[14]: b # In[15]: c # You cannot reassign values in a tuple. They are immutable! # In[16]: x[0] = 4 # ## Dictionary # # Dictionaries are a way to efficient store and retrieve `keyword: value` type data. For example: # In[17]: my_dict = {'numerical' : 1, 'alphabetical': 'abc'} # Then we can look up the value of `'numerical'` quickly: # In[18]: my_dict['numerical'] # Or `'alphabetical'` # In[19]: my_dict['alphabetical'] # Just likes lists, you can have a dictionary-of-dictionaries # In[20]: my_dict = {'numerical' : {'linear solver' : 'gmres'}, 'alphabetical': 'abc'} # To return the value of `'linear solver'` directly # In[21]: my_dict['numerical']['linear solver']