Mutable or immutable

Python objects can be mutable or immutable. If an object is mutable, the value to the object can be updated with a different value. For immutable object, a new object is created if user tries to update the value of the object.

Numbers in Python are immutable. You can find the id of an object by using id(variable_name) to find the id of an object.

Numbers

Integers in Python can have unlimited range. The size of the value is only bounded by the virtual memory that is usable in the machine.

You can use int() function to convert string to integer value. It will also convert number with decimal to an integer value by truncating the trailing decimal values.

Python has build-in power functions. To specify power, 2 formats exists:

  1. pow(10, 3) will raise 10 to the 3rd power. The result will be a float number (ie. 1000.0)
  2. 10**3 will also raise 10 to the 3rd power. The result will be an integer (1000)

Real Numbers

Real numbers are floating point numbers that are represented with IEEE 754 standard. It is stored in 64 bits of information that contains sign, exponent, and mantissa.

Double precision (64-bit) representation of float number suffers from approximation issue. This is not a good choice for banking or even e-commerce application where precise representation for decimals is crucial. Use Decimal type from Python as it doesn’t suffer from the imprecision from 64-bit numerical presentation.

Strings and bytes

Python string objects are immutable and they are sequences of unicode code point. Python doesn’t have a char type like some other programming languages. You just have a string with length of 1.

While internally Python strings are encoded with unicode, sometime it is beneficial to encode the string in bytes object while transferring string over the network, etc.

Python string can be written with single, double or triple quotes. String in the triple quotes can span across multiple lines without worrying about end of line characters, spaces, tabs, etc.

To find the length of a string, use len(variable_name) function.

[Python 3.9] Two new methods that are introduced that allows you to remove prefix or suffix from a string. To remove prefix, use removeprefix(‘remove_string’). To remove suffix, use removesuffix(‘remove_string’).

Example: s = ‘Hello There’.
s.removeprefix(‘Hell’) will produce result -> ‘o There’
s.removesuffix(‘here’) will produce result -> ‘Hello T’
If the input parameter doesn’t exist within the string, you will simply get the original string back without any error message.

To encode and decode strings

We can encode Unicode string and decode byte objects. One common character encoding scheme is UTF-8. To create a bytes object from a string declaration, append b in front of the string.

Example: s = “This is a string”
type(s) — display <class, ‘str’>
encoded_s = s.encode(‘utf-8’) # to encode string to utf-8
type(encoded_s) — display <class, ‘bytes’>
encoded_s.decode(‘utf-8’) # returns the original string

Indexing and Slicing strings

You can create sub-sequences from a given string using indexing and slicing operation.

You specify slicing operation with the following my_sequence[start:stop:step] where start is inclusive and stop is exclusive (means if you wrote 7 for start parameter, you will start at 7 but if you wrote 7 for stop, it will stop one before 7 which will be 6).

Some examples:
s = “The trouble is you think you have time.”
s[0] => returns ‘T’
s[5] => returns ‘r’
s[:4] => returns ‘The ‘ note: 4 is not inclusive.
s[2:14] => returns ‘e trouble is’
s[4:] => ‘trouble is you think you have time.’ since 4 is starting index which is inclusive.
s[2:14:3] => returns ‘erb ‘ since it starts at index 2, stops at index 13 (since 14 is not inclusive) in the increment of 3.
s[:] => returns the whole string. People often uses this to make a copy of string.
s[::-1] => return a reversed version of the string.

String Formatting

Some simple way to format strings in Python.

greet_positional = ‘Hello {} {}’
greet_positional.format(‘John’, ‘Smith’) –> Hello John Smith
greet_positional_idx = ‘This is {0}! {1} loves {0}!’
greet_positional_idx.format(‘Python’, ‘John’) –> This is Python! John loves Python!

[Python 3.6 -] Formatted String Literal (or F-String)

name = ‘Fab’
age = 42
f”Hello! My name is {name} and I’m {age}” –> Hello! My name is Fab and I’m 42

Tuples

A tuple can contain a sequence of arbitrary Python objects so the type of objects stored in the tuple doesn’t have to be homogeneous. Items in the tuple are separated by commas and for tuple with just one element still need to be terminate with a comma after the object.

Example:
t = () # this is empty tuple declaration.
t = (42, ) # this is one element tuple
three_element_tuple = (1, 2, 5)
a, b, c = 1, 2, 3 => a, b, c == (1, 2, 3)

Lists

List is very similar to tuple but it is mutable. Just like tuple, you can store heterogeneous data into it.
To create an empty list:
a = list() or a = []
create a list from tuple: a = list((1, 2, 3,4))
a = [1, 2, 3, 4]
a.append(5) will insert 5 at the end of a list.
a.count(1) # will return 1 as it provide the number of 1s in list.
a.extend([5, 6]) # this will extend the list with list provided.
a.index(3) # return 2 as it will provide the first index with the content 2
a.insert(0, 17) # will insert 17 in the list at position 0
a.pop() # will return and remove the last element from the list
a.pop(2) # will return and remove element from position 2
a.remove(17) # will remove value 17 from the list
a.reverse() # return a list with revered elements
a.sort() # sort the elements
a.clear() # remove all elements from the list.

Common operations for list

a = [1, 3, 5, 7]
min(a) # will return 1
max(a) # will return 7
sum(a) # will return 16
len(a) # will return 4 which is the number of elements in the list
b = [6, 7, 8]
a + b = [1, 3, 5, 6, 7, 8] # basically append list b to list a.

Byte Array

This represent mutable version of bytes array. Each element can contain an integer in the range of 0-255.

Set

Python provides 2 set types and they are set and frozenset. Frozen set is immutable version and set is mutable. Hashability is a characteristic that allows an object to be used as a set member as well as a key for a dictionary.

myset = set() or myset = {}
myset.add(2) # add 2 to the set
myset.remove(2) # remove 2 from the set
2 in myset # returns True as it test from membership
2 not in myset # return False as it tests membership using negation.
bigset = {5, 7, 11, 13}
myset | bigset => {2, 5, 7, 11, 13} # union operation that will include values from both sets.
myset & bigset => {} # intersection that returns values that belong to both set.

Dictionaries (or Map)

Dictionary maps keys to values. Keys must be hashable objects since they have to be unique. Values can be any arbitrary objects.

To declare dictionary:
a = dict(a=1, z=-1) or b = {‘a’: 1, ‘b’: -1}

One function that often gets used with dictionary is zip() function. Zip function will pair the 2 lists together and use value from list as the key and pair the elements from the other list and use it as the value.
Example:
list(zip([‘h’,’e’,’l’,’l’,’o’], [1, 2, 3, 4, 5]) will return [(‘h’, 1), (‘e’, 2), (‘l’, 3), (‘l’, 4), (‘o’, 5)]

d = {} # create an empty dictionary
d[‘a’] = 1 # {‘a’:1}
d[‘b’] = 2 # {‘a’: 1, ‘b’:2}
len(d) # returns 2
d[‘a’] # returns 1
del[‘a’] # remove element ‘a’ from dictionary
‘a’ in d # return True as it tests membership in dictionary d for key a.
d.keys() # returns the keys in a list.
d.values() # return the values in a list.
d.items() # return the items in a list paired in the tuple.
d.popitem() # removes a random item and return the item.
d.pop(‘a’) # removes a item with key ‘a’.
d.pop(‘a’, ‘default-value’) # remove item with key ‘a’, if key ‘a’ doesn’t exist, return ‘default-value’ or what every object it is appropriate.

Categories:

Tags:

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *

Cookie Consent with Real Cookie Banner