Types in Python
Types in Python
None
The None object is used to represent the absence of a value. It is similar to null in other programming
languages. Like other "empty" values, such as 0, [] and the empty string, it is False when converted to a
Boolean variable.
if None:
print("None got interpreted as True")
else:
print("None got interpreted as False")
Output:
>>> None got interpreted as False
The None object is returned by any function that doesn't explicitly return anything else.
def some_func():
print("Hi!")
var = some_func()
print(var)
Try It Yourself
Result: >>>
Hi!
None
>>>
What number does this code print?
foo = print()
if foo == None:
print(1) #answer is 1
else:
print(2)
Dictionaries
Dictionaries are data structures used to map arbitrary keys to values. Lists can be thought of as
dictionaries with integer keys within a certain range. Dictionaries can be indexed in the same way as
lists, using square brackets containing keys.
Example:
Result: >>>
24
42
>>>
Each element in a dictionary is represented by a key:value pair.
key should be unique in the dictionary while values need not be unique
Return:
24
42
John
Key:value
Trying to index a key that isn't part of the dictionary returns a KeyError.
Example:
primary = {
"red": [255, 0, 0],
"green": [0, 255, 0],
"blue": [0, 0, 255],
}
print(primary["red"])
print(primary["yellow"])
Result: >>>
[255, 0, 0]
KeyError: 'yellow'
>>>
As you can see, a dictionary can store any types of data as values.
test = { }
print(test[0])
None
0
KeyError
Only immutable objects can be used as keys to dictionaries. Immutable objects are those that can't be
changed. So far, the only mutable objects you've come across are lists and dictionaries. Trying to use a
mutable object as a dictionary key causes a TypeError.
bad_dict = {
[1, 2, 3]: "one two three",
}
Result: >>>
TypeError: unhashable type: 'list'
>>>
Dictionaries functions
Just like lists, dictionary keys can be assigned to different values. However, unlike lists, a new dictionary
key can also be assigned a value, not just ones that already exist.
To determine whether a key is in a dictionary, you can use in and not in, just as you can for a list.
Example:
nums = {
1: "one",
2: "two",
3: "three",
}
print(1 in nums)
print("three" in nums)
print(4 not in nums)
>>>
True
False
True
>>>
A useful dictionary method is get. It does the same thing as indexing, but if the key is not found in the
dictionary it returns another specified value instead ('None', by default).
Example:
pairs = {1: "apple",
"orange": [2, 3, 4],
True: False,
None: "True",
}
print(pairs.get("orange"))
print(pairs.get(7))
print(pairs.get(12345, "not in dictionary"))
Result: >>>
[2, 3, 4]
None
not in dictionary
Tuples
Tuples are very similar to lists, except that they are immutable (they cannot be changed).
Also, they are created using parentheses, rather than square brackets.
Example:
You can access the values in the tuple with their index, just as you did with lists:
print(words[0])
words[1] = "cheese"
Result: >>> TypeError: 'tuple' object does not support item assignment
Like lists and dictionaries, tuples can be nested within each other.
Why use tuples? Because they require less processing power from Python because they're immutable.
Doesn't make a big diff in small programmes but if you're working on a big project it will improve speed
and efficiency.
Tuples can also be "packed" and "unpacked" which can be very useful for creating variables
>>
Apple
Pear
Banana
Tuples can be created without the parentheses, by just separating the values with commas.
Example:
my_tuple = "one", "two", "three"
print(my_tuple[0])
Try It Yourself
Result:>>>
one
>>>
An empty tuple is created using an empty parenthesis pair.tpl = ()
List Slices
List slices provide a more advanced way of retrieving values from a list. Basic list slicing involves indexing
a list with two colon-separated integers. This returns a new list containing all the values in the old list
between the indices.
Example:
Example:
squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
print(squares[:7])
print(squares[7:])
Result: >>>
[0, 1, 4, 9, 16, 25, 36]
[49, 64, 81]
Slicing can also be done on tuples.
[0, 1, 4]
An error occurs
[1, 25]
[1, 25, 81]
Negative values can be used in list slicing (and normal list indexing). When negative values are used for
the first and second values in a slice (or a normal index), they count from the end of the list.
List Comprehensions
List comprehensions are a useful way of quickly creating lists whose contents obey a simple rule.
# a list comprehension
Result: >>>
[0, 1, 8, 27, 64]
>>>
A list comprehension can also contain an if statement to enforce a condition on values in the list.
Example:
evens=[i**2 for i in range(10) if i**2 % 2 == 0]
Result: >>>
[0, 4, 16, 36, 64]
>>>
Trying to create a list in a very extensive range will result in a MemoryError.
This code shows an example where the list comprehension runs out of memory.
Result: >>>
MemoryError
>>>
This issue is solved by generators, which are covered in the next module.
String Formatting
So far, to combine strings and non-strings, you've converted the non-strings to strings and added them.
String formatting provides a more powerful way to embed non-strings within strings. String formatting
uses a string's format method to substitute a number of arguments in the string.
Example:
# string formatting
nums = [4, 5, 6]
msg = "Numbers: {0} {1} {2}". format(nums[0], nums[1], nums[2])
print(msg)
Result:>>>
Numbers: 4 5 6
>>>
Each argument of the format function is placed in the string at the corresponding position, which is
determined using the curly braces { }.
Example:
a = "{x}, {y}".format(x=5, y=12)
print(a)
Result:>>> 5, 12
What is the result of this code?
5, 9, 7
9, 7, 5
7, 9, 5
String Functions
Python contains many useful built-in functions and methods to accomplish common tasks.
print("This is a sentence.".startswith("This"))
# prints "True"
print("This is a sentence.".endswith("sentence."))
# prints "True"
print("This is a sentence.".upper())
# prints "THIS IS A SENTENCE."
Numeric Functions
To find the maximum or minimum of some numbers or a list, you can use max or min.
To find the distance of a number from zero (its absolute value), use abs.
To round a number to a certain number of decimal places, use round.
To find the total of a list, use sum.
Some examples:
print(min(1, 2, 3, 4, 0, 2, 1))
print(max([1, 4, 9, 2, 5, 6, 8]))
print(abs(-99))
print(abs(42))
print(sum([1, 2, 3, 4, 5]))
Result: >>>
0
9
99
42
15
List Functions
Often used in conditional statements, all and any take a list as an argument, and return True if all or any
(respectively) of their arguments evaluate to True (and False otherwise).
The function enumerate can be used to iterate through the values and indices of a list simultaneously.
Example:
for v in enumerate(nums):
print(v)
Result: >>>
All larger than 5
At least one is even
(0, 55)
(1, 44)
(2, 33)
(3, 22)
(4, 11)
Text Analyzer
This is an example project, showing a program that analyzes a sample file to find what percentage of the
text each character occupies.
This section shows how a file could be open and read. filename = input("Enter a filename: ")
with open(filename) as f:
text = f.read()
print(text)
Result:
>>>
Enter a filename: test.txt
Ornhgvshy vf orggre guna htyl.
Rkcyvpvg vf orggre guna vzcyvpvg.
Fvzcyr vf orggre guna pbzcyvpngrq.
Syng vf orggre guna arfgrq.
Fcenfr fv orggre guna qrafr.
Ernqnovyvgl pbhagf.
Fcrpvny pnfrf nera'g fcrpvny rabthu gb oernx gur ehyrf.
Nygubhtu cenpgvpnyvgl orgnf chevgl.
Reebef fubhyq arire cnff fvyragyl.
Hayrff rkcyvpvgyl fvyraprq.
Va gur snpr bs nzovthvgl, ershfr gur grzcgngvba bg thrff.
Gurer fubhyq or bar-- naq cersrenoylbayl bar --boivbhf jnl gb qb vg.
Nygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu.
Abj vf orggre guna arrire.
Nygubhtu arire vf bsgra orggre guna *evtug* abj.
Vs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn.
Vs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn.
Anzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!
This part of the program shows a function that counts how many times a character occurs in a string.
This function takes as its arguments the text of the file and one character, returning the number of times
that character appears in the text.
Now we can call it for our file. filename = input("Enter a filename: ")
with open(filename) as f:
text = f.read()
print(count_char(text, "r"))
Result: >>>
Enter a filename: test.txt
83
>>>
The character "r" appears 83 times in the file.
The next part of the program finds what percentage of the text each character of the alphabet occupies.
for char in "abcdefghijklmnopqrstuvwxyz":
print(max(min(nums[:2]), abs(-42)))