Python Essentials - Part 2 - Data Types Flashcards
What Python Integers?
Integers
Python integers have an unlimited range, subject only to the available virtual memory. This means that it doesn’t really matter how big a number you want to store is: as long as it can it in your computer’s memory, Python will take care of it. Integer numbers can be positive,negative, and 0 (zero).
They support all the basic mathematical operations, as shown in the following example:
>>> a = 14
>>> b = 3
>>> a + b # addition
17
>>> a - b # subtraction
11
>>> a * b # multiplication
42
>>> a / b # true division
4.666666666666667
>>> a // b # integer division
4
>>> a % b # modulo operation (reminder of division)
2
>>> a ** b # power operation
2744
Did you know? Python version feature
Python 3.6 Introduced the ability to add underscores within number literals (between digits or base specifiers, but not leading or trailing). The purpose is to help make some numbers more readable, like for example 1_000_000_000
>>> n = 1_024
>>> n
1024
>>> hex_n = 0x_4_0_0 # 0x400 == 1024
>>> hex_n
1024
What are Python Real Numbers?
Real numbers, or floating point numbers, are represented in Python according to the IEEE 754 double-precision binary floating point format, which is stored in 64 bits of information divided into three sections: sign, exponent, and mantissa.
Several programming languages give coders two different formats: single and double precision. The former takes up 32 bits of memory, the latter 64. Python supports only the double format.
What are Python Booleans?
Boolean algebra is that subset of algebra in which the values of the variables are the truth values: true and false. In Python, True and False are two keywords that are used to represent truth values.
Booleans are a subclass of integers, and behave respectively like 1 and 0.
The equivalent of the int class for Booleans is the bool class, which returns either True or False. Every built-in Python object has a value in the Boolean context, which means they basically evaluate to either True or False when fed to the bool function.
What are Python Complex Numbers?
Python gives you complex numbers support out of the box. If you don’t know what complex numbers are, they are numbers that can be expressed in the form a + ib, where a and b are real numbers, and i (or j if you’re an engineer) is the imaginary unit; that is, the square root of -1. a and b are called, respectively, the real and imaginary part of the number.
It is perhaps unlikely that you will use them, unless you’re coding something scientific.
What is Upcasting?
**Upcasting** is a type conversion operation that goes from a subclass to its parent. In the example presented here, **True** and **False**, which belong to a class **derived** from the **integer class**, are **converted back to integers** when needed.
>>> 1 + True
2
>>> False + 42
42
>>> 7 - True
6
Mutable vs immutable?
The first fundamental distinction that Python makes on data is about whether or not the value of an object can change. If the value can change, the object is called mutable, whereas if the value cannot change, the object is called immutable.
It is very important that you understand the distinction between mutable and immutable because it affects the code you write;
Python Immutable sequences?
- Strings
- Tuples
- Bytes
Python Strings and bytes?
Textual data in Python is handled with str objects, more commonly known as strings. They are immutable sequences of Unicode code points. Unicode code points can represent a character, but can also have other meanings, such as when formatting, for example. Python, unlike other languages, doesn’t have a char type, so a single character is rendered simply by a string of length 1.
Unicode is an excellent way to handle data, and should be used for the internals of any application. When it comes to storing textual data though, or sending it on the network, you will likely want to encode it, using an appropriate encoding for the medium you are using. The result of an encoding produces a bytes object, whose syntax and behavior is similar to that of strings. String literals are written in Python
using single, double, or triple quotes (both single or double).
What is formatted string literals(f””)?
- Added in Python in version 3.6
- Faster than using the format() method
- sample f”Hello! My name is {name} and I’m {age}”
What is formatted string literals(f””) additions ?
- Introduced in Python 3.8
>>> user = ‘heinrich’
>>> password = ‘super-secret’
>>> f”Log in with: {user} and {password}”
‘Log in with: heinrich and super-secret’
>>> f”Log in with: {user=} and {password=}”
“Log in with: user=’heinrich’ and password=’super-secret’”
What is Python Tuple?
A tuple is a sequence of arbitrary Python objects. In a tuple declaration, items are separated by commas. Tuples are used everywhere in Python. They allow for patterns that are quite hard to reproduce in other languages. Sometimes tuples are used implicitly;
for example, to set up multiple variables on one line, or to allow a function to return multiple objects (in several languages, it is common for a function to return only one object), and in the Python console, tuples can be used implicitly to print multiple elements with one single instruction.
>>> t = () # empty tuple
>>> type(t)
class ‘tuple’
>>> one_element_tuple = (42, ) # you need the comma!
>>> three_elements_tuple = (1, 3, 5) # braces are optional here
>>> a, b, c = 1, 2, 3 # tuple for multiple assignment
>>> a, b, c # implicit tuple to print with one instruction
(1, 2, 3)
>>> 3 in three_elements_tuple # membership test
True
NB: my_tuple = 1, 2, 3 is the same as my_tuple = (1, 2, 3).
Python Mutable sequences?
Mutable sequences differ from their immutable counterparts in that they can be changed after creation. There are two mutable sequence types in Python:
- Lists
- Byte arrays.
What are Python List data-type?
Python lists are very similar to tuples, but they don’t have the restrictions of immutability. Lists are commonly used for storing collections of homogeneous objects, but there is nothing preventing you from storing heterogeneous collections as well. Lists can be created in many different ways.
>>> [] # empty list
[]
>>> list() # same as []
[]
>>> [1, 2, 3] # as with tuples, items are comma separated
[1, 2, 3]
>>> [x + 5 for x in [2, 3, 4]] # Python is magic
[7, 8, 9]
>>> list((1, 3, 5, 7, 9)) # list from a tuple
[1, 3, 5, 7, 9]
>>> list(‘hello’) # list from a string
[‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
>>> a = [1, 2, 1, 3]
>>> a.append(13) # we can append anything at the end
>>> a
[1, 2, 1, 3, 13]
>>> a.count(1) # how many 1s
are there in the list?
2
>>> a.extend([5, 7]) # extend the list by another (or sequence)
>>> a
[1, 2, 1, 3, 13, 5, 7]
>>> a.index(13) # position of 13
in the list (0-based indexing)
4
>>> a.insert(0, 17) # insert 17
at position 0
>>> a
[17, 1, 2, 1, 3, 13, 5, 7]
>>> a.pop() # pop (remove and return) last element
7
>>> a.pop(3) # pop element at position 3
1
>>> a
[17, 1, 2, 3, 13, 5]
>>> a.remove(17) # remove 17
from the list
>>> a
[1, 2, 3, 13, 5]
>>> a.reverse() # reverse the order of the elements in the list
>>> a
[5, 13, 3, 2, 1]
>>> a.sort() # sort the list
>>> a
[1, 2, 3, 5, 13]
>>> a.clear() # remove all elements from the list
>>> a
[]
>>> a = list(‘hello’) # makes a list from a string
>>> a
[‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
>>> a.append(100) # append 100, heterogeneous type
>>> a
[‘h’, ‘e’, ‘l’, ‘l’, ‘o’, 100]
>>> a.extend((1, 2, 3)) # extend using tuple
>>> a
[‘h’, ‘e’, ‘l’, ‘l’, ‘o’, 100, 1, 2, 3]
>>> a.extend(‘…’) # extend using string
>>> a
[‘h’, ‘e’, ‘l’, ‘l’, ‘o’, 100, 1, 2, 3, ‘.’, ‘.’, ‘.’]
What are the common list operations?
>>> a = [1, 3, 5, 7]
>>> min(a) # minimum value in the list
1
>>> max(a) # maximum value in the list
7
>>> sum(a) # sum of all values in the list
16
>>> from math import prod
>>> prod(a) # product of all values in the list
105
>>> len(a) # number of elements in the list
4
>>> b = [6, 7, 8]
>>> a + b # +
with list means concatenation
[1, 3, 5, 7, 6, 7, 8]
>>> a * 2 # *
has also a special meaning
[1, 3, 5, 7, 1, 3, 5, 7]
>>> from operator import itemgetter
>>> a = [(5, 3), (1, 3), (1, 2), (2, -1), (4, 9)]
>>> sorted(a)
[(1, 2), (1, 3), (2, -1), (4, 9), (5, 3)]
>>> sorted(a, key=itemgetter(0))
[(1, 3), (1, 2), (2, -1), (4, 9), (5, 3)]