Lists

Lists are a mutable data structure which can be modified in-place without creating a new list, and can follow any specifc order. Can be accessed by offset.

List creation and description

In [1]:
north_america = ["Canada", "Mexico", "USA", "Cuba", "Jamaica"] # creating an empty list: empty_list = [] or empty_list = list()
In [2]:
print(north_america)
['Canada', 'Mexico', 'USA', 'Cuba', 'Jamaica']
In [3]:
type(north_america)
Out[3]:
list
In [4]:
len(north_america)         #returns an integer representing the number of elements in the list
Out[4]:
5

Slicing and Indexing

       [ Start : End ]

[ Inclusive : Exclusive ]

Start at index 1 and get all elements to the right

In [5]:
north_america[1:]    #Start at index 1, to the end of list
Out[5]:
['Mexico', 'USA', 'Cuba', 'Jamaica']

Start at index 0, end at index 2 but do not include it.

In [6]:
north_america[0:2]   #Start at index 0, end at index 2 but do not include it.
Out[6]:
['Canada', 'Mexico']

Start at the end of the list with -1 and move backwords until the -3rd element

In [7]:
north_america[-3]    #Working backwards from -1 (which is the last element in the list) (returns a string because single element)
Out[7]:
'USA'
In [8]:
nested_list = ["Canada", "Mexico", ["USA", ["California",["Palo Alto", "Redwood City"],"Michigan"]], "Cuba", "Jamaica"]
In [9]:
print(nested_list)
['Canada', 'Mexico', ['USA', ['California', ['Palo Alto', 'Redwood City'], 'Michigan']], 'Cuba', 'Jamaica']
In [10]:
print(nested_list[2])
['USA', ['California', ['Palo Alto', 'Redwood City'], 'Michigan']]
In [11]:
nested_list[2][1][1][0]
Out[11]:
'Palo Alto'

Assigning, Appending, Inserting and Deleting objects/elements in a list

Assigning in place

In [12]:
north_america[0] = "Haiti"                                      #in place index assignment (over-writing indexed element)
print(north_america)
['Haiti', 'Mexico', 'USA', 'Cuba', 'Jamaica']

Appending (adding to the end of the list)

In [13]:
north_america.append("Belize")                                   #in place adding to the end of the list
print(north_america)
['Haiti', 'Mexico', 'USA', 'Cuba', 'Jamaica', 'Belize']

Insert at spcified index

In [14]:
north_america.insert(0, "Canada")                                #insert element at index specified pushing elements to the right
print(north_america)
['Canada', 'Haiti', 'Mexico', 'USA', 'Cuba', 'Jamaica', 'Belize']

Delete element at a specified index

In [15]:
del north_america[1]        #similar to >>  north_america.pop(1)
print(north_america)        #           >>  'Haiti'
['Canada', 'Mexico', 'USA', 'Cuba', 'Jamaica', 'Belize']

Insert at a spcecified negative index

In [16]:
north_america.insert(-1, "Haiti") #same as north_america.insert(5, "Haiti")
In [17]:
print(north_america)
['Canada', 'Mexico', 'USA', 'Cuba', 'Jamaica', 'Haiti', 'Belize']

Creating another list

In [18]:
north_america2 = ["Panama", "Costa Rica", "Puerto Rico"]    #New list of more North American countries.

Adding a list to a list using the extend method

In [19]:
north_america.extend(north_america2)  #Extends our list to include the new list (changes in place).
                                      #north_america + north_america2 (creates a whole new list, doesnt change in place)
In [20]:
print(north_america)
['Canada', 'Mexico', 'USA', 'Cuba', 'Jamaica', 'Haiti', 'Belize', 'Panama', 'Costa Rica', 'Puerto Rico']

Removing an element of a list by name

In [21]:
north_america.remove("Belize")                              #Remove element of the list by name (not index location)
In [22]:
print(north_america)
['Canada', 'Mexico', 'USA', 'Cuba', 'Jamaica', 'Haiti', 'Panama', 'Costa Rica', 'Puerto Rico']

Removing an element using the pop method

In [23]:
north_america.pop() #by default removes last item in a list.  .pop(index) can be used to remove by index.
                    #returns item that's removed as a str.   (which can be used to capure the element)
                    #ex. >> removed_countries = []
                    #    >> removed_countries.append(north_america.pop())           "Puerto Rico"
                    #    >> removed_countries.append(north_america.pop(2))          "USA"
                    #    >> print(removed_countries)
                    #    ["Puerto Rico", "USA"]
Out[23]:
'Puerto Rico'
In [24]:
print(north_america)
['Canada', 'Mexico', 'USA', 'Cuba', 'Jamaica', 'Haiti', 'Panama', 'Costa Rica']

Copying a list

In [25]:
northamerica = north_america[:]                         #copy north_america list elements to northamerica list
In [26]:
print(id(north_america), id(northamerica))              #two distinct lists
2629128981192 2629130272264

Removing all elements from the list

In [27]:
northamerica.clear()     # removes all items from list.  del northamerica[:] is the same.b
In [28]:
print(northamerica)
[]

Sorting & Search

The sort method will sort a list in place. The sort functions will return a new sorted list

Sorting using the sorted function

In [29]:
sorted(north_america) # returns a sorted list of north_america (alphabetical)
Out[29]:
['Canada', 'Costa Rica', 'Cuba', 'Haiti', 'Jamaica', 'Mexico', 'Panama', 'USA']
In [30]:
print(north_america)  # nothing changed
['Canada', 'Mexico', 'USA', 'Cuba', 'Jamaica', 'Haiti', 'Panama', 'Costa Rica']

Sorting using the sort method

In [31]:
north_america.sort() #sorts in-place (no new varaible needed) .sort() method is avaiable to lists.
In [32]:
print(north_america)
['Canada', 'Costa Rica', 'Cuba', 'Haiti', 'Jamaica', 'Mexico', 'Panama', 'USA']

Sorting using the sort method with the reverse arguement

In [33]:
north_america.sort(reverse=True) #Reverses list using reverse arguement.   -- sorted(north_america, reverse=True)
In [34]:
print(north_america)
['USA', 'Panama', 'Mexico', 'Jamaica', 'Haiti', 'Cuba', 'Costa Rica', 'Canada']

Sorting using the reverse method

In [35]:
north_america.reverse() # reverses order in-place
In [36]:
print(north_america)
['Canada', 'Costa Rica', 'Cuba', 'Haiti', 'Jamaica', 'Mexico', 'Panama', 'USA']
In [37]:
print("Belize" in north_america)
False
In [38]:
print("Jamaica" in north_america)
True

Using the index those to get index location

In [39]:
north_america.index("Jamaica")           # returns is 4. what is 4?
Out[39]:
4
In [40]:
type(north_america.index("Jamaica"))     # 4 is an integer, we can work with that!
Out[40]:
int
In [41]:
north_america[north_america.index("Jamaica")] = "Bahamas"   #north_america[4] = "Bahamas"
In [42]:
print(north_america)
['Canada', 'Costa Rica', 'Cuba', 'Haiti', 'Bahamas', 'Mexico', 'Panama', 'USA']

Tuples

A tuple is an immutable data structure which cannot be modified after it has been created. A tuple has a defined order, just like a list.

Tuple creation and description

In [43]:
continents =("Europe", "Asia", "Africa", "North America", "South America", "Antarctica", "Australia") # empty_tuple = ()   or
                                                                                                      # empty_tuple = tuple()
In [44]:
print(continents)   #kept the order
('Europe', 'Asia', 'Africa', 'North America', 'South America', 'Antarctica', 'Australia')
In [45]:
type(continents)
Out[45]:
tuple
In [46]:
len(continents)      # 7 elements in our continents
Out[46]:
7

Slicing & Indexing

       [ Start : End ]

[ Inclusive : Exclusive ]

In [47]:
continents[1:]       #Start at index 1, to the end of list
Out[47]:
('Asia', 'Africa', 'North America', 'South America', 'Antarctica', 'Australia')
In [48]:
continents[0:2]     #Start at index 0, end at index 2 but do not include it.
Out[48]:
('Europe', 'Asia')
In [49]:
continents[-3]      #Working backwards from -1 (which is the last element in the list) 
Out[49]:
'South America'

Assigning, Appending, Inserting and Deleting objects/elements in a tuple? [Fail]

In [50]:
continents[0] = "Pangaea" #error because tuples are immutable
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-50-3e84f04fec78> in <module>()
----> 1 continents[0] = "Pangaea" #error because tuples are immutable

TypeError: 'tuple' object does not support item assignment
In [51]:
continents.append("Pangaea") #error: method not available to tuples
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-51-2a82be6f9102> in <module>()
----> 1 continents.append("Pangaea") #error: method not available to tuples

AttributeError: 'tuple' object has no attribute 'append'
In [52]:
continents.insert(0, "Pangaea")  #error: method not available to tuples
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-52-be4bf8f61019> in <module>()
----> 1 continents.insert(0, "Pangaea")  #error: method not available to tuples

AttributeError: 'tuple' object has no attribute 'insert'
In [53]:
del continents[1] #error because tupes are immutable
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-53-ccf0b3640dc6> in <module>()
----> 1 del continents[1] #error because tupes are immutable

TypeError: 'tuple' object doesn't support item deletion

Sorting [Fail] & Search

The sorted function on a tuple will return a new sorted LIST. Sort methods are not avaiable to a tuple due to the fact that a tuple is immutable.

In [54]:
sorted(continents) #  returns a sorted LIST of continents (alphabetical)  
Out[54]:
['Africa',
 'Antarctica',
 'Asia',
 'Australia',
 'Europe',
 'North America',
 'South America']
In [55]:
print(continents)  # nothing changed 
('Europe', 'Asia', 'Africa', 'North America', 'South America', 'Antarctica', 'Australia')
In [56]:
continents.sort()  # error sort method not available to tuples (immutable)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-56-8d585e62910a> in <module>()
----> 1 continents.sort()  # error sort method not available to tuples (immutable)

AttributeError: 'tuple' object has no attribute 'sort'

Failed to sort due to immutability of tuples. We can sort lists though, so lets use them.

In [57]:
print(id(continents))                    # Lets get the id of our tuple for fun.
2629111626040
In [58]:
continents = sorted(continents)          #Lets use the function that spits out a sorted LIST.
In [59]:
print(id(continents), type(continents))  #Our tuple is gone. =(
2629130459464 <class 'list'>
In [60]:
continents=tuple(continents)             #lets cheat a little by converting our new list back to a tuple
In [61]:
type(continents)
Out[61]:
tuple
In [62]:
print(continents)                        #Alas, we have a sorted tuple.
('Africa', 'Antarctica', 'Asia', 'Australia', 'Europe', 'North America', 'South America')
In [63]:
print(id(continents))                    # New tuple created for our sorted list.
2629111626040
In [64]:
print("Africa" in continents)
True

 

 

 

In [65]:
splitme = "create a tuple"
splitme.split()
Out[65]:
['create', 'a', 'tuple']
In [66]:
newtuple = 'create', 'a', 'tuple'  # another way to create a tuple
In [67]:
newtuple
Out[67]:
('create', 'a', 'tuple')
In [68]:
z,y,x = newtuple                 # tuple unpacking. same as (z,y,x) = newtuple  
In [69]:
z,y,x
Out[69]:
('create', 'a', 'tuple')

Sets

Sets are a mutable data structure that contain unique elements. Elements in a set do not retain order because sets do not record element position or order of insertion. All elements in a set should immutable.

Set creation and description

In [70]:
seta = {1, 2, 3, 2}                      #empty_set = set()
setb = {2, 3, 4, 3}                      # can create from string  setc = set('python') -> ~ {'h', 'p', 't', 'n', 'o', 'y'}
In [71]:
empty_set = set()
In [72]:
print(" seta {} \n setb {}".format(seta, setb))   #duplicate elements were removed from seta and setb respectively
 seta {1, 2, 3} 
 setb {2, 3, 4}
In [73]:
print(empty_set)                      # this is what an empty set looks like
set()
In [74]:
type(seta)
Out[74]:
set
In [75]:
len(seta)
Out[75]:
3

Slicing & Indexing? [Fail]

A set does not rank or order elements therefore we are unable to slice or index a set.

In [76]:
seta[1:] 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-76-b7bcb075c148> in <module>()
----> 1 seta[1:]

TypeError: 'set' object is not subscriptable
In [77]:
seta[:2]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-77-f29f9fc305ab> in <module>()
----> 1 seta[:2]

TypeError: 'set' object is not subscriptable
In [78]:
seta[-3]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-78-dc54f04ed2f9> in <module>()
----> 1 seta[-3]

TypeError: 'set' object does not support indexing

Assigning, Appending, Inserting and Deleting objects/elements in a set?

In [79]:
seta[0] = 3         # sets do not retain order therefore we are unable to assign a element to a specific index  
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-79-f2ce9c0595c7> in <module>()
----> 1 seta[0] = 3         # sets do not retain order therefore we are unable to assign a element to a specific index

TypeError: 'set' object does not support item assignment
In [80]:
seta.add(4)         # the .append method doesnt exist for sets but the .add method does. (changes in place)
In [81]:
print(" seta {} \n setb {}".format(seta, setb))
 seta {1, 2, 3, 4} 
 setb {2, 3, 4}
In [82]:
setb.add(5)         # adding the int 5 to set b (changes in place)
In [83]:
setb.add(7)         # adding another element to set b
In [84]:
print(" seta {} \n setb {}".format(seta, setb))
 seta {1, 2, 3, 4} 
 setb {2, 3, 4, 5, 7}
In [85]:
setb.remove(4)      # remove the integer 4 from our setb
In [86]:
print(" seta {} \n setb {}".format(seta, setb))
 seta {1, 2, 3, 4} 
 setb {2, 3, 5, 7}
In [87]:
#seta.pop()          # removes and returns an arbitrary element from seta. Raises error if set is empty
In [88]:
print(" seta {} \n setb {}".format(seta, setb))
 seta {1, 2, 3, 4} 
 setb {2, 3, 5, 7}
In [89]:
seta.update(setb)                               # adds elements from setb to seta. Ignoring duplicates, keeping unique elements.
In [90]:
print(" seta {} \n setb {}".format(seta, setb))
 seta {1, 2, 3, 4, 5, 7} 
 setb {2, 3, 5, 7}
In [91]:
seta.discard(7)
In [92]:
print(" seta {} \n setb {}".format(seta, setb))
 seta {1, 2, 3, 4, 5} 
 setb {2, 3, 5, 7}
In [93]:
seta.discard(7)                                 # .discard method raises no error even if 7 is not in set.   
In [94]:
seta.remove(66)                                 # .remove method raises error because element is not in set.
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-94-16ab1a9d595b> in <module>()
----> 1 seta.remove(66)                                 # .remove method raises error because element is not in set.

KeyError: 66
In [95]:
seta.clear()                                   # removes all elements from seta
In [96]:
setb.clear()                                   # removes all elements from setb
In [97]:
print(" seta {} \n setb {}".format(seta, setb))
 seta set() 
 setb set()

Union, Intersect, Difference, & Symmetric Difference

In [98]:
seta = {1, 2, 3, 2}                 
setb = {2, 3, 4, 3} 
print(" seta {} \n setb {}".format(seta, setb))
 seta {1, 2, 3} 
 setb {2, 3, 4}

Union

In [99]:
print((seta) | (setb))  #  (Union: in list a, b or both) 
                        #  seta.union(setb)
{1, 2, 3, 4}

Intersect

In [100]:
print((seta) & (setb))  #  (Intersect: only if member of both)
                        #  seta.intersection(setb)
{2, 3}

Difference ( a - b )

In [101]:
print((seta) - (setb))  #  (Set difference: if member in a but not b)
                        #  seta.difference(setb)
{1}

Difference ( b - a )

In [102]:
print((setb) - (seta))  #  (Set difference: if member in b but not a)
                        #  setb.difference(seta)
{4}

Symmetric difference

In [103]:
print((seta) ^ (setb)) # (Symmetric difference: if member in a or b but not both)
                       # Finding the same items and removing them  
                       # seta.symmetric_difference(setb)   or  ((seta) - (setb) | (setb) - (seta))
{1, 4}

Sorting [Fail] & Search

A set is unable to be sorted in place, we can similarly do what we did with a tuple but it is futile as we will lose order when we convert the sorted list back to a set.

In [104]:
us_states = {'California', 'Texas', 'Nevada', 'Washington', 'Arizona', 'Michigan'}
print(us_states)                                                #Elements in set already changed order
{'Texas', 'Washington', 'Arizona', 'California', 'Nevada', 'Michigan'}
In [105]:
us_states = sorted(us_states)                           # making a sorted list out of our set
print(us_states) 
['Arizona', 'California', 'Michigan', 'Nevada', 'Texas', 'Washington']
In [106]:
us_states = set(us_states)                              # converting out sorted list to a set
print(us_states)                                        # we lost our sort due to the nature of sets
{'Texas', 'Washington', 'Arizona', 'California', 'Nevada', 'Michigan'}
In [107]:
print("Ohio" in us_states)
False
In [108]:
print("Arizona" in us_states)
True
In [109]:
west_coast = {"California", "Washington"}     # created new set 
west_coast.issubset(us_states)                # Returns true if ALL elements in west_coast are in us_states
Out[109]:
True
In [110]:
us_states.issubset(west_coast)                # Returns false because all elements in us_states are not in west_coast
Out[110]:
False
In [111]:
west_coast.issuperset(us_states)              # Returns false becasue ALL elements in us_states are not in west_coast
Out[111]:
False
In [112]:
us_states.issuperset(west_coast)              # Returns true because all elements in west_coast are in us_states)
Out[112]:
True

Dictionaries

Dictionaries are a key, value pair data structure. Keys have to be immutable while values can contain mutable elements. Typically dictionaries do not retain order.* Dictionaries can grow or shrink in place with out creating a new dictionary.

        Key : Value

{ "name" : "isaac" }

Dictionary creation and description

In [113]:
empty_dict = {}    # empty_dict = dict() (constructor)
In [114]:
scientist = {"name": "albert einstein", "age": 50, "residence": ["Germany", "United States"]}
In [115]:
print(scientist)
{'name': 'albert einstein', 'age': 50, 'residence': ['Germany', 'United States']}
In [116]:
type(scientist)
Out[116]:
dict
In [117]:
len(scientist)      # 3 key-value pairs in scientist dict.
Out[117]:
3

Slicing & Indexing

We can't slice or index dictionaries as we can with lists. Dictionaries can't be accessed by offset but rather by key.

In [118]:
scientist[2]            # error 
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-118-f7c0ca1ec64f> in <module>()
----> 1 scientist[2]            # error

KeyError: 2
In [119]:
scientist["name"]       # 
Out[119]:
'albert einstein'
In [120]:
scientist["age"]
Out[120]:
50
In [121]:
scientist["residence"]                  # index using the residence key returns us a list
Out[121]:
['Germany', 'United States']
In [122]:
scientist["residence"][1]               # we are now indexing a list at index 1
Out[122]:
'United States'
In [123]:
scientist["education"]                  # error because education key does not exist
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-123-94a07e7a0b78> in <module>()
----> 1 scientist["education"]                  # error because education key does not exist

KeyError: 'education'
In [124]:
scientist.get("name")                   # another way to retrieve the values of the name key
Out[124]:
'albert einstein'
In [125]:
scientist.get("education")             # .get method does not raise an error if key is not in dictionary
In [126]:
scientist.get("education", "Information not available")  # infact, we can specify a default return value if key is not in dict.
Out[126]:
'Information not available'
In [127]:
scientist.keys()                        # returns the key elements 
Out[127]:
dict_keys(['name', 'age', 'residence'])
In [128]:
scientist.values()                      # returns the value elements
Out[128]:
dict_values(['albert einstein', 50, ['Germany', 'United States']])
In [129]:
scientist.items()                        # returns the key and value elements
Out[129]:
dict_items([('name', 'albert einstein'), ('age', 50), ('residence', ['Germany', 'United States'])])

Assigning, Appending, Inserting and Deleting objects/elements in a dictionary

Replacing a current value in a spcified key.

In [130]:
scientist["name"]  = "Albert Einstein"     # replaces old value of "name" with a new one in place
In [131]:
print(scientist)
{'name': 'Albert Einstein', 'age': 50, 'residence': ['Germany', 'United States']}

Create a new key - value pair

In [132]:
scientist["education"] = ["Swiss Federal Polytechnic", "University of Zurich"]  # Adds a new key called education and
                                                                                # a new value which in this case is a list.
In [133]:
print(scientist)
{'name': 'Albert Einstein', 'age': 50, 'residence': ['Germany', 'United States'], 'education': ['Swiss Federal Polytechnic', 'University of Zurich']}
In [134]:
scientist_description = dict(year_born=1979, year_death=1955, birthplace="Germany")  #create a new dict using dict constructor
In [135]:
print(scientist_description)
{'year_born': 1979, 'year_death': 1955, 'birthplace': 'Germany'}
In [136]:
scientist.update(scientist_description)              # adds scientist_description dict to scientist dict
In [137]:
print(scientist)
{'name': 'Albert Einstein', 'age': 50, 'residence': ['Germany', 'United States'], 'education': ['Swiss Federal Polytechnic', 'University of Zurich'], 'year_born': 1979, 'year_death': 1955, 'birthplace': 'Germany'}
In [138]:
scientist.update({"name": "Albert 'Dopey' Einstein", "age": 51}) # update the "name" value to include Einsteins nickname
In [139]:
print(scientist)
{'name': "Albert 'Dopey' Einstein", 'age': 51, 'residence': ['Germany', 'United States'], 'education': ['Swiss Federal Polytechnic', 'University of Zurich'], 'year_born': 1979, 'year_death': 1955, 'birthplace': 'Germany'}
In [140]:
del scientist['year_death']                 # removes the key and value of year_death
In [141]:
print(scientist)
{'name': "Albert 'Dopey' Einstein", 'age': 51, 'residence': ['Germany', 'United States'], 'education': ['Swiss Federal Polytechnic', 'University of Zurich'], 'year_born': 1979, 'birthplace': 'Germany'}
In [142]:
scientist.pop('year_born')                # pops (removes) the key year_born, returning us the value it also removed.
Out[142]:
1979
In [143]:
print(scientist)
{'name': "Albert 'Dopey' Einstein", 'age': 51, 'residence': ['Germany', 'United States'], 'education': ['Swiss Federal Polytechnic', 'University of Zurich'], 'birthplace': 'Germany'}
In [144]:
#scientist.popitem()                      # Removes and returns an arbitrary (key, value) pair 
In [145]:
#scientist.clear()                        # Removes all elements of dict.

Sorting & Search

There is not a native way to sort a dictionary. Python 3.6 boasts that it can preserve the order of dictionary. If that's the case we can create a couple functions will enable us to index a key or a value using an integer index

In [146]:
print(scientist)
{'name': "Albert 'Dopey' Einstein", 'age': 51, 'residence': ['Germany', 'United States'], 'education': ['Swiss Federal Polytechnic', 'University of Zurich'], 'birthplace': 'Germany'}
In [147]:
def get_keyindex(dictionary, n=0):
    if n < 0:
        n += len(dictionary)
    for i, key in enumerate(dictionary.keys()):
        if i == n:
            return key
    raise IndexError("dictionary index out of range") 
    
def get_nth_valueindex(dictionary, n=0):
    if n < 0:
        n += len(dictionary)
    for i, values in enumerate(dictionary.values()):
        if i == n:
            return values
    raise IndexError("dictionary index out of range") 
In [148]:
(get_keyindex(scientist,-1))
Out[148]:
'birthplace'
In [149]:
scientist[get_keyindex(scientist,0)] = "Alberto Einsteino"
In [150]:
print(scientist)
{'name': 'Alberto Einsteino', 'age': 51, 'residence': ['Germany', 'United States'], 'education': ['Swiss Federal Polytechnic', 'University of Zurich'], 'birthplace': 'Germany'}
In [151]:
print ("name" in scientist)        
True
In [152]:
print ("year_born" in scientist)
False

List Comprehension

First way to square a list.

In [153]:
mylist = [1,2,3,4,5]      # create a new list
In [154]:
squared_list= []
for x in mylist:         #we want to square our list
    squared_list.append(x ** 2)
In [155]:
print(squared_list)
[1, 4, 9, 16, 25]

Second way to square a list.

In [156]:
def squared(list):
    squared_list = []
    for x in list:
        squared_list.append(x ** 2)
    return squared_list
In [157]:
squared(mylist)
Out[157]:
[1, 4, 9, 16, 25]

List comprehension way to square a list

In [158]:
print( [x**2 for x in mylist] )
[1, 4, 9, 16, 25]

[ expr for val in collection ]

[ expr for val in collection if boolean ]

[ expr for val in collection if boolean and boolean]

[ expr for val1 in collection and val2 in collection2]

Saving our returned list to a variable

In [159]:
mysquare = [x**2 for x in mylist] 

Dictionary comprehension

In [160]:
{x: x**2 for x in mylist}
Out[160]:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Zip

In [161]:
list_1 = [1,3,5,6,7,8]
list_2 = ['Toyota', "Honda", "Nissan", "Tesla", "Acura", "Mercedez"]
In [162]:
myzip = zip(list_1, list_2)           # zips list_1 and list_2 binding it to the my zip variable
In [163]:
print (type(myzip))                   # zip iterator
<class 'zip'>
In [164]:
print(myzip )                                
<zip object at 0x00000264245B79C8>
In [165]:
for x in myzip:
    print(x)
(1, 'Toyota')
(3, 'Honda')
(5, 'Nissan')
(6, 'Tesla')
(7, 'Acura')
(8, 'Mercedez')
In [166]:
for x in myzip:                        # because zip produces an iterator that can only be traversed once trying to access it
    print(x)                           # again yields no result 

We need to "caputre" the zip results

In [167]:
myzip = [list(elements) for elements in zip(list_1, list_2)]     # List comprehension does the job 
                                                                 # notice that we re-initiated the zip function on our list
                                                                 # comprehension. We could use the myzip variable if we 
                                                                 # re-initiate the zip the is bound to it
In [168]:
print(myzip)
[[1, 'Toyota'], [3, 'Honda'], [5, 'Nissan'], [6, 'Tesla'], [7, 'Acura'], [8, 'Mercedez']]
In [169]:
for list_1, list_2 in zip(list_1, list_2):  
    print(list_1, list_2)
1 Toyota
3 Honda
5 Nissan
6 Tesla
7 Acura
8 Mercedez
In [170]:
list_1                         # in a for loop last element is stored
Out[170]:
8
In [171]:
list_2                         # in a for loop last element is stored
Out[171]:
'Mercedez'

Need to reinitialize origial list_1 and list_2

In [172]:
list_1 = [1,3,5,6,7,8]
list_2 = ['Toyota', "Honda", "Nissan", "Tesla", "Acura", "Mercedez"]
In [173]:
anotherzip = list(zip(list_1, list_2))
In [174]:
print(anotherzip)
[(1, 'Toyota'), (3, 'Honda'), (5, 'Nissan'), (6, 'Tesla'), (7, 'Acura'), (8, 'Mercedez')]
In [175]:
anotherdict = dict(zip(list_1, list_2))
In [176]:
print(anotherdict)
{1: 'Toyota', 3: 'Honda', 5: 'Nissan', 6: 'Tesla', 7: 'Acura', 8: 'Mercedez'}

Split

In [177]:
"by default the method splits on spaces".split()   
Out[177]:
['by', 'default', 'the', 'method', 'splits', 'on', 'spaces']
In [178]:
myaddress = 'isaac@navigoamnis.org'
In [179]:
myaddress.split("@")                                          # override the default. We want to split at the @ key.
Out[179]:
['isaac', 'navigoamnis.org']
In [180]:
username, domain = myaddress.split("@")
In [181]:
print("My name is {} and my damain is {} " .format(username, domain))
My name is isaac and my damain is navigoamnis.org 

Key Sorting

In [182]:
def ourKey(item):                             #Lets define a function to use as a key to sort by.
    return item[0]                            #We will sort by first element in tuple, [1] would sort by second element of tuple.
In [183]:
tuple_a = ((4, 6), (32, 8), (1, 13), (21, 42), (8, 21))   #Creating a tuple of tuples
In [184]:
sorted(tuple_a, key=ourKey)                               #We get back a sorted list of our tuples (first index).
Out[184]:
[(1, 13), (4, 6), (8, 21), (21, 42), (32, 8)]
In [185]:
tuple_a                                                   #Orginal tuple is unchanged (immutable)
Out[185]:
((4, 6), (32, 8), (1, 13), (21, 42), (8, 21))
In [186]:
tuple_a = tuple(sorted(tuple_a, key=ourKey))              #Need to convert list of tuples fromt sort function to tuple.
In [187]:
print(tuple_a)
((1, 13), (4, 6), (8, 21), (21, 42), (32, 8))

Misc

Creating a new dict using a list of specified keys.

In [188]:
numdict= {0:1, 1:2, 2:3, 3:4, 4:5, 5:8, 6:12, 11:15, 42:17, 50:20, 54:32, 62:47}
keys = (0, 1, 2, 6, 50, 62)
newnumdict = {k: numdict[k] for k in keys}
In [189]:
print(newnumdict)
{0: 1, 1: 2, 2: 3, 6: 12, 50: 20, 62: 47}

Iterating through our keys and values of the scientist dict.

In [190]:
for key in scientist.keys():
    values = scientist[key]
    print(key, "=", values)
name = Alberto Einsteino
age = 51
residence = ['Germany', 'United States']
education = ['Swiss Federal Polytechnic', 'University of Zurich']
birthplace = Germany

Squaring a list using numpy

In [191]:
import numpy as np
b = list(np.array(mylist)**2)
In [192]:
print(b)
[1, 4, 9, 16, 25]

Flatten a list

In [193]:
myzip                 # here we have a list of list (myzip came from zip section)
Out[193]:
[[1, 'Toyota'],
 [3, 'Honda'],
 [5, 'Nissan'],
 [6, 'Tesla'],
 [7, 'Acura'],
 [8, 'Mercedez']]
In [194]:
flat_list = []
for sublist in myzip:
    for elements in sublist:
        flat_list.append(elements)
In [195]:
flat_list
Out[195]:
[1, 'Toyota', 3, 'Honda', 5, 'Nissan', 6, 'Tesla', 7, 'Acura', 8, 'Mercedez']
In [196]:
flat_list2 = [elements for sublist in myzip for elements in sublist]      #list comprehension way.
In [197]:
flat_list2
Out[197]:
[1, 'Toyota', 3, 'Honda', 5, 'Nissan', 6, 'Tesla', 7, 'Acura', 8, 'Mercedez']