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.
north_america = ["Canada", "Mexico", "USA", "Cuba", "Jamaica"] # creating an empty list: empty_list = [] or empty_list = list()
print(north_america)
type(north_america)
len(north_america) #returns an integer representing the number of elements in the list
north_america[1:] #Start at index 1, to the end of list
north_america[0:2] #Start at index 0, end at index 2 but do not include it.
north_america[-3] #Working backwards from -1 (which is the last element in the list) (returns a string because single element)
nested_list = ["Canada", "Mexico", ["USA", ["California",["Palo Alto", "Redwood City"],"Michigan"]], "Cuba", "Jamaica"]
print(nested_list)
print(nested_list[2])
nested_list[2][1][1][0]
north_america[0] = "Haiti" #in place index assignment (over-writing indexed element)
print(north_america)
north_america.append("Belize") #in place adding to the end of the list
print(north_america)
north_america.insert(0, "Canada") #insert element at index specified pushing elements to the right
print(north_america)
del north_america[1] #similar to >> north_america.pop(1)
print(north_america) # >> 'Haiti'
north_america.insert(-1, "Haiti") #same as north_america.insert(5, "Haiti")
print(north_america)
north_america2 = ["Panama", "Costa Rica", "Puerto Rico"] #New list of more North American countries.
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)
print(north_america)
north_america.remove("Belize") #Remove element of the list by name (not index location)
print(north_america)
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"]
print(north_america)
northamerica = north_america[:] #copy north_america list elements to northamerica list
print(id(north_america), id(northamerica)) #two distinct lists
northamerica.clear() # removes all items from list. del northamerica[:] is the same.b
print(northamerica)
The sort method will sort a list in place. The sort functions will return a new sorted list
sorted(north_america) # returns a sorted list of north_america (alphabetical)
print(north_america) # nothing changed
north_america.sort() #sorts in-place (no new varaible needed) .sort() method is avaiable to lists.
print(north_america)
north_america.sort(reverse=True) #Reverses list using reverse arguement. -- sorted(north_america, reverse=True)
print(north_america)
north_america.reverse() # reverses order in-place
print(north_america)
print("Belize" in north_america)
print("Jamaica" in north_america)
north_america.index("Jamaica") # returns is 4. what is 4?
type(north_america.index("Jamaica")) # 4 is an integer, we can work with that!
north_america[north_america.index("Jamaica")] = "Bahamas" #north_america[4] = "Bahamas"
print(north_america)
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.
continents =("Europe", "Asia", "Africa", "North America", "South America", "Antarctica", "Australia") # empty_tuple = () or
# empty_tuple = tuple()
print(continents) #kept the order
type(continents)
len(continents) # 7 elements in our continents
continents[1:] #Start at index 1, to the end of list
continents[0:2] #Start at index 0, end at index 2 but do not include it.
continents[-3] #Working backwards from -1 (which is the last element in the list)
continents[0] = "Pangaea" #error because tuples are immutable
continents.append("Pangaea") #error: method not available to tuples
continents.insert(0, "Pangaea") #error: method not available to tuples
del continents[1] #error because tupes are immutable
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.
sorted(continents) # returns a sorted LIST of continents (alphabetical)
print(continents) # nothing changed
continents.sort() # error sort method not available to tuples (immutable)
Failed to sort due to immutability of tuples. We can sort lists though, so lets use them.
print(id(continents)) # Lets get the id of our tuple for fun.
continents = sorted(continents) #Lets use the function that spits out a sorted LIST.
print(id(continents), type(continents)) #Our tuple is gone. =(
continents=tuple(continents) #lets cheat a little by converting our new list back to a tuple
type(continents)
print(continents) #Alas, we have a sorted tuple.
print(id(continents)) # New tuple created for our sorted list.
print("Africa" in continents)
splitme = "create a tuple"
splitme.split()
newtuple = 'create', 'a', 'tuple' # another way to create a tuple
newtuple
z,y,x = newtuple # tuple unpacking. same as (z,y,x) = newtuple
z,y,x
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.
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'}
empty_set = set()
print(" seta {} \n setb {}".format(seta, setb)) #duplicate elements were removed from seta and setb respectively
print(empty_set) # this is what an empty set looks like
type(seta)
len(seta)
A set does not rank or order elements therefore we are unable to slice or index a set.
seta[1:]
seta[:2]
seta[-3]
seta[0] = 3 # sets do not retain order therefore we are unable to assign a element to a specific index
seta.add(4) # the .append method doesnt exist for sets but the .add method does. (changes in place)
print(" seta {} \n setb {}".format(seta, setb))
setb.add(5) # adding the int 5 to set b (changes in place)
setb.add(7) # adding another element to set b
print(" seta {} \n setb {}".format(seta, setb))
setb.remove(4) # remove the integer 4 from our setb
print(" seta {} \n setb {}".format(seta, setb))
#seta.pop() # removes and returns an arbitrary element from seta. Raises error if set is empty
print(" seta {} \n setb {}".format(seta, setb))
seta.update(setb) # adds elements from setb to seta. Ignoring duplicates, keeping unique elements.
print(" seta {} \n setb {}".format(seta, setb))
seta.discard(7)
print(" seta {} \n setb {}".format(seta, setb))
seta.discard(7) # .discard method raises no error even if 7 is not in set.
seta.remove(66) # .remove method raises error because element is not in set.
seta.clear() # removes all elements from seta
setb.clear() # removes all elements from setb
print(" seta {} \n setb {}".format(seta, setb))
seta = {1, 2, 3, 2}
setb = {2, 3, 4, 3}
print(" seta {} \n setb {}".format(seta, setb))
print((seta) | (setb)) # (Union: in list a, b or both)
# seta.union(setb)
print((seta) & (setb)) # (Intersect: only if member of both)
# seta.intersection(setb)
print((seta) - (setb)) # (Set difference: if member in a but not b)
# seta.difference(setb)
print((setb) - (seta)) # (Set difference: if member in b but not a)
# setb.difference(seta)
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))
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.
us_states = {'California', 'Texas', 'Nevada', 'Washington', 'Arizona', 'Michigan'}
print(us_states) #Elements in set already changed order
us_states = sorted(us_states) # making a sorted list out of our set
print(us_states)
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
print("Ohio" in us_states)
print("Arizona" in us_states)
west_coast = {"California", "Washington"} # created new set
west_coast.issubset(us_states) # Returns true if ALL elements in west_coast are in us_states
us_states.issubset(west_coast) # Returns false because all elements in us_states are not in west_coast
west_coast.issuperset(us_states) # Returns false becasue ALL elements in us_states are not in west_coast
us_states.issuperset(west_coast) # Returns true because all elements in west_coast are in us_states)
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.
empty_dict = {} # empty_dict = dict() (constructor)
scientist = {"name": "albert einstein", "age": 50, "residence": ["Germany", "United States"]}
print(scientist)
type(scientist)
len(scientist) # 3 key-value pairs in scientist dict.
We can't slice or index dictionaries as we can with lists. Dictionaries can't be accessed by offset but rather by key.
scientist[2] # error
scientist["name"] #
scientist["age"]
scientist["residence"] # index using the residence key returns us a list
scientist["residence"][1] # we are now indexing a list at index 1
scientist["education"] # error because education key does not exist
scientist.get("name") # another way to retrieve the values of the name key
scientist.get("education") # .get method does not raise an error if key is not in dictionary
scientist.get("education", "Information not available") # infact, we can specify a default return value if key is not in dict.
scientist.keys() # returns the key elements
scientist.values() # returns the value elements
scientist.items() # returns the key and value elements
scientist["name"] = "Albert Einstein" # replaces old value of "name" with a new one in place
print(scientist)
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.
print(scientist)
scientist_description = dict(year_born=1979, year_death=1955, birthplace="Germany") #create a new dict using dict constructor
print(scientist_description)
scientist.update(scientist_description) # adds scientist_description dict to scientist dict
print(scientist)
scientist.update({"name": "Albert 'Dopey' Einstein", "age": 51}) # update the "name" value to include Einsteins nickname
print(scientist)
del scientist['year_death'] # removes the key and value of year_death
print(scientist)
scientist.pop('year_born') # pops (removes) the key year_born, returning us the value it also removed.
print(scientist)
#scientist.popitem() # Removes and returns an arbitrary (key, value) pair
#scientist.clear() # Removes all elements of dict.
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
print(scientist)
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")
(get_keyindex(scientist,-1))
scientist[get_keyindex(scientist,0)] = "Alberto Einsteino"
print(scientist)
print ("name" in scientist)
print ("year_born" in scientist)
mylist = [1,2,3,4,5] # create a new list
squared_list= []
for x in mylist: #we want to square our list
squared_list.append(x ** 2)
print(squared_list)
def squared(list):
squared_list = []
for x in list:
squared_list.append(x ** 2)
return squared_list
squared(mylist)
print( [x**2 for x in mylist] )
mysquare = [x**2 for x in mylist]
{x: x**2 for x in mylist}
list_1 = [1,3,5,6,7,8]
list_2 = ['Toyota', "Honda", "Nissan", "Tesla", "Acura", "Mercedez"]
myzip = zip(list_1, list_2) # zips list_1 and list_2 binding it to the my zip variable
print (type(myzip)) # zip iterator
print(myzip )
for x in myzip:
print(x)
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
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
print(myzip)
for list_1, list_2 in zip(list_1, list_2):
print(list_1, list_2)
list_1 # in a for loop last element is stored
list_2 # in a for loop last element is stored
list_1 = [1,3,5,6,7,8]
list_2 = ['Toyota', "Honda", "Nissan", "Tesla", "Acura", "Mercedez"]
anotherzip = list(zip(list_1, list_2))
print(anotherzip)
anotherdict = dict(zip(list_1, list_2))
print(anotherdict)
"by default the method splits on spaces".split()
myaddress = 'isaac@navigoamnis.org'
myaddress.split("@") # override the default. We want to split at the @ key.
username, domain = myaddress.split("@")
print("My name is {} and my damain is {} " .format(username, domain))
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.
tuple_a = ((4, 6), (32, 8), (1, 13), (21, 42), (8, 21)) #Creating a tuple of tuples
sorted(tuple_a, key=ourKey) #We get back a sorted list of our tuples (first index).
tuple_a #Orginal tuple is unchanged (immutable)
tuple_a = tuple(sorted(tuple_a, key=ourKey)) #Need to convert list of tuples fromt sort function to tuple.
print(tuple_a)
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}
print(newnumdict)
for key in scientist.keys():
values = scientist[key]
print(key, "=", values)
import numpy as np
b = list(np.array(mylist)**2)
print(b)
myzip # here we have a list of list (myzip came from zip section)
flat_list = []
for sublist in myzip:
for elements in sublist:
flat_list.append(elements)
flat_list
flat_list2 = [elements for sublist in myzip for elements in sublist] #list comprehension way.
flat_list2