About lists
Features
・Enclose in square brackets
・Set each element with commas
・Retrieve elements by specifying the index
list = ['element1','element2','element3','element4']
^0 ^1 ^2 ^3
^-4 ^-3 ^-2 ^-1
x = list[0] # x contains “Element 1”
y = list[-2] # y contains “Element 3”
・Split the list by specifying an index
list[start position:end position]
list = ['element1','element2','element3','element4']
^0 ^1 ^2 ^3 ^4
^-4 ^-3 ^-2 ^-1
# Omit start position [:3]
>>> From the first position to the third
# Omit end position [2:]
>>> From the second to the last element
# Omit all [:]
>>> Get all values
・Empty list (zero elements)
x = []
y = list()
・Adding elements
x = [10,20,30]
x.append(40)
・Removing elements
x = [10,20,30]
x.remove(20)
・Deleting elements ②
# pop([i]) deletes the element at the specified position from the list and returns that list.
x = [10,20,30]
print(x.pop(1))
>>> 20
・Can have elements with the same value
x = ['a','b','a']
About dictionaries
Features
・Can have multiple pairs of keys and values
・Cannot have elements with the same key (values are OK)
dictionary = {key1:value1,key2:value2,key3:value3}
scores = {'Japanese':82,'Math':70,'English':74}
• Retrieve the value of a key by specifying the key
x = dictionary.get(key)
# In the above example...
jpn = scores.get('Japanese') # 82
• Retrieve only the key/value pair
dictionary.keys()
# In the above example...
x = scores.keys() # ['Japanese','Mathematics','English']
dictionary.values()
# In the above example...
y = scores.values() # [82, 70, 74]
・Retrieve the number of elements in the dictionary
len(dictionary)
# In the above example...
z = len(scores) # 3
・Empty dictionary
x = {}
y = dict()
About sets
Features
・A collection of multiple values
・No order (cannot specify an index)
・Cannot have duplicate values
x = {1,2,3}
• Adding elements
set.add(element)
x = {1,2,3}
x.add(4)
• Removing elements
set.discard(element) # No error even if the specified element is not in the set
set.remove(element) # Error if the specified element is not in the set
・Set operations
x = {1,2,4,6}
y = {1,3,5,7}
z = x | y # Union
z = x - y # Difference
z = x & y # Intersection
About tuples
Features
・Multiple values combined into one
・Ordered
・Can have the same values
・Values cannot be changed (immutable)
x = (1 , 2 , 3)
^0 ^1 ^2
y = x[2] # 3