print('Winter' + 'Park')
WinterPark
Python basics
Chi Zhang
December 2, 2024
Resources: Python Data Science Handbook by Jake VanderPlas
Check data types
Mutable | Ordered | Indexing | Duplicates | |
---|---|---|---|---|
Lists | Yes | Yes | Yes | Yes |
Tuples | - | Yes | Yes | Yes |
Sets | Yes | - | - | - |
Square brackets
list1 = ['tea', 'jam', 'scone']
list1
# different types of data can be mixed
list2 = ['tea', 20, True]
list2
['tea', 20, True]
Index starts from 0
Lists are mutable, you can change the values in the list after it’s created.
Index can also be used on a string. However strings are immutable: we can not replace a character with another.
The stopping index is exclusive: [0:2]
prints out the 1st and 2nd element.
animals =["cat", "dog", "bird", "cow"]
print(animals[0:2]) # excludes 0, takes 1st and 2nd
print(animals[1:3]) # excludes 1, takes 2nd and 3rd
['cat', 'dog']
['dog', 'bird']
The immediate two indices prints out only one value.
A easier way to remember this for [a:b]
, start counting from [a+1:b]
. Example: [3:5]
becomes the 4th and 5th; [2:3]
becomes 3rd and 3rd - just the 3rd.
Ignoring the starting index or stopping index
cart = ['lamp', 'candles', 'chair', 'carpet']
print(cart[:2]) # stopping at 2nd
print(cart[1:]) # starting at 2nd
['lamp', 'candles']
['candles', 'chair', 'carpet']
Negative indexing
Syntax: <variable> = [<expression> for <item> in <iterable>]
nums = []
for x in range(1,11):
nums.append(x)
print(nums)
# alternatively,
nums = [x for x in range(1, 11)]
nums
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
<variable> = [<expression> for <item> in <iterable>]
nums = [x*2 for x in range(10)]
nums
tags = ['travel', 'vacation']
hashtags = ['#' + x for x in tags]
hashtags
# capitalise
Tags = [x.capitalize() for x in tags]
Tags
['Travel', 'Vacation']
Can combine conditions too
()
Use parentheses. Tuples are immutable, they are useful when data shouldn’t be accidentally modified. Therefore you can not use append
functions on tuples.
# of 7: 1
# of 9: 3
Unpacking in tuple. The length needs to be matched; however if you want to deal with unknown number of elements, can use *
. After unpacking, the elements becomes a list []
.
{}
With curly brackets. Sets are unordered so does not support indexing or slicing.
{'Jonathan', 'Anna', 'Mery'}
Sets can not have duplicates, and duplicates are automatically ignored
Sets are mutable, so you can add
and remove
items. However, append
does not work on sets since they are unordered.
{'Jonathan', 'Anna', 'Robert'}
To clear the set,
To join sets, use set1.union(set2)
. This ignores the duplicates. To find the element only in set 1 but not set 2, use set1.difference(set2)
The values can be of any type, including a list. The keys has to be immutable.
{'name': 'pen', 'is_red': True, 'price': 79}
When the key is a string, it needs to go with quotation.
The key has to be unique. If duplicate, the values will be overwritten.
{'name': 'maria', 'company': 'facebook'}
To access the values, use ['key']
contact['company']
contact.get('company')
contact.get('baba', 'puff') # if baba does not exist, returns puff
'puff'
dict_items([('name', 'maria'), ('company', 'facebook')])
Change values for dictionary with update()
user = {
'name': 'Albert',
'age': 29
}
user.update({'age': 30})
print(user['age'])
print(user.items())
30
dict_items([('name', 'Albert'), ('age', 30)])
pop()
removes item with specified key name
car = {
'brand': 'Ford',
'model': 'mustang',
'color': 'red'
}
# remove color key
car.pop('color')
print(car)
# check if values are in the dictionary
'mustang' in car.values()
{'brand': 'Ford', 'model': 'mustang'}
True
Combined with loops, it returns the keys (not values)
car = {
'brand': 'Ford',
'model': 'mustang',
'color': 'red'
}
for i in car:
print(i)
for i in car.values(): # this prints the values
print(i)
for i in car.items(): # this prints the pairs
print(i)
brand
model
color
Ford
mustang
red
('brand', 'Ford')
('model', 'mustang')
('color', 'red')
Unpack dictionary with **