python data structures - ghdrako/doc_snipets GitHub Wiki

Create data structer using formal name

formal_list = list()
formal_dict = dict()
formal_tuple = tuple()

Literal syntax

literal_list = []
literal_dict = {}
literal_tuple = ()

List

x = [5, 3.0, 10, 200.2]
x = ['JupytherNB', 75, None, True, [34, False], 2, 75] 
x[4] = 52
len(x)
y = [9, 0, 4, 2]
print(x + y) # to concatenate two lists, + operator is used
print(y * 3) # to concatenate multiple copies of the same list, * operator is used
z = [y, x]   # to nest lists to create another list

Slicing

use a colon to specify the start point (inclusive) and end point (noninclusive) of the sub-list

x[0:4] # the last element seen in the output is at index 3
x[:4]
x[4:]
x[-2:]
x[0:4:2] # steps of 2
x[4::-2] # start from the element at index 4 and go backward to the beginning with steps of 2

Modifing

x.append(-23)
x.remove(75)
y.sort() # to sort the element of y
x.insert(2, 10) # insert(pos, elmnt) method inserts the specified elmntat the specified position (pos) and shift the rest to the right
print(x.pop(3)) # pop(pos) method removes (and returns) the element at the specified position (pos)
del x[1] # delete an element from a list by its index
x.pop() # by default the position is -1, which means that it removes the last element

Coping

Shallow copies

>>>list1 = ['A+', 'A', 'B', 'C+']
>>>list2 = list1
>>>list2.append('D')
>>>print(list2)
>>>print(list1)
['A+', 'A', 'B', 'C+', 'D']
['A+', 'A', 'B', 'C+', 'D']

Deep copy

>>>list3 = list1[:] # the use of slicing; that is, using [:] we make a deep copy of the entire list1
>>>list3.append('E')
>>>print(list3)
>>>print(list1)
['A+', 'A', 'B', 'C+', 'D', 'E']
['A+', 'A', 'B', 'C+', 'D']


list4 = list1.copy() # the use of copy() method
list4.append('E')
print(list4)
print(list1)

list5 = list(list1) #the use of list() constructor
list5.append('E')
print(list5)
print(list1)

List functions

  • len(list)
  • min(list)
  • max(list)
  • sum(list)
  • sorted(list) # return new list sorted in ascending order
  • reversed(list) # return reversed iterator
  • list.count(element) # number of times element appear on list
  • list.extend(iterable)
  • list.clear() # remove elements from list

Tuples

tuple1 = ('Machine', 'Learning', 'with', 'Python', '1.0.0')
tuple1[0]
tuple1[::2]
len(tuple1)
tuple1 = ('Jupyter', 'NoteBook') # redefine tuple1
tuple2 = tuple1 + ('Good', 'Morning')

Imutable so can be use as key in dictionaries or elements in set because they are hashable (have unique value to identify them)

coordinates={(0,0):"Origin",(1,1):"Point A",(2,4):"Point B"}
print(coordinates[(0,0)]

Set

colors={("r","g","b"),("y","m","c"),("b","w")}
print(("b","w") in colors) # True

Note Tuples can be only hashable if all its elements are hashable as well. For example tuple contain list cannot be use as key in dictionary or element in set because list is mutable - not hashable

sequence packing

In Python, a sequence of comma separated objects without parentheses is packed into a tuple.

tuple1 = 'Machine', 'Learning', 'with', 'Python', '1.0.0' # sequence packing
x, y, z, v, w = tuple1 # the use of sequence unpacking
### unpacking the list
list6 = ['Machine', 'Learning', 'with', 'Python', '1.0.0']
x, y, z, v, w = list6

if we want to create a one-element tuple, the comma is required

tuple3 = 'Machine',
type(tuple3)

Dictionaries

dict1 = {1:'value for key 1', 'key for value 2':2, (1,0):True, False:[100,50], 2.5:'Hello'}
dict1['key for value 2'] # accessed item using the keys
dict1['key for value 2'] = 30 # change an element
dict1[10] = 'Bye' # add new item
del dict1['key for value 2']
(1,0) in dict1.keys()   # check the membership in keys
(1,0) in dict1 # equivalent to: in dict1.keys()
"Hello" in dict1.values() # check the membership in values
dict2 = dict([('Police', 102), ('Fire', 101), ('Gas', 104)]) # create dict from list of tuples pair
dict3 = dict(Country='USA', phone_numbers=dict2, population_million=18.7) # the use of keywords arguments = object

### Set

set1 = {'a', 'b', 'c', 'd', 'e'} set2 = {'b', 'b', 'c', 'f', 'g'} set1 | set2 # union using an operator set1.union(set2) set1 & set2 # intersection set1.intersection(set2) set1 - set2 # difference: elements of set1 not in set2 set1.difference(set2) set1 ^ set2 # symmetric difference: elements only in one set, not in both set1.symmetric_difference(set2) 'b' in set1 # check membership