Python
/
Collections
- 1 Language 9
-
Hello World S
-
Variables S
-
Functions S
-
Conditional A S
-
Operators S
-
While S
-
Turtle S
-
Script Mode S
-
Debugging S
- 2 Strings 7
-
Slice S
-
Raw Strings S
-
Regex A S
-
Validation S
-
Config S
-
Security S
-
Encrypt A S
- 3 Collections 6
-
Lists S
-
Dictionaries S
-
Efficiency S
-
Tree S
-
Tuples S
-
References S
- 4 Functions 5
-
Recursion S
-
Factorial S
-
Modulus S
-
Reassignment S
-
Approximate S
- 5 Storage 8
-
Files S
-
Databases S
-
Pipes S
-
With open S
-
Shelve A S
-
Zip S
-
Csv S
-
Json S
- 6 Class 4
-
Definition S
-
Attributes S
-
Functional S
-
Methods S
- 7 Goodies 5
-
Conditional Expression S
-
List Comprehension A S
-
Generator S
-
Named Tuple S
-
Modules S
- 8 Applications 5
-
Pythagora A S
-
Palindrome A S
-
Binary Search A S
-
Conway Game A S
-
Coin Flip A S
- 9 Scheduler 4
-
Time S
-
Multithreading A S
-
Subprocess S
-
Logging S
- 10 Packages 6
-
Clipboard A S
-
Ocr A S
-
Socket S
-
Image S
-
Virtualenv S
-
Jupyter S
S
R
Q
Python Collections Lists
Lists are mutable (unlike strings) Use + to concatenate lists A = [1, 2]; A[1] = 3 A == [1, 3] # true
Mutable
p163 Unlike strings, lists are mutable.
"""Lists are mutable
A list contains multiple values in an ordered sequence
"""
A = [1, 2]; A[1] = 3
assert A == [1, 3]
assert A != [1, 2]
print('Tests passed')
Concat
p167 You can use the + operator concatenate lists.
"""To concatenate two list use + operator
To multiply a list use * operator
"""
A = [1, 2] + [3,4]
B = [9] * 4
C = A * 2
assert A == [1, 2, 3, 4]
assert B == [9, 9, 9, 9]
assert C == [1, 2, 3, 4, 1, 2, 3, 4]
print('Tests passed')
Slice
The slice operator also works on lists.
""" Slice operator [:] works on list, as with strings
The value -1 refers to the last index in a list
"""
a = "abcde"
assert a[:1] == "a"
assert a[1:] == "bcde"
assert a[1:3] == "bc" # limit 3 not included
A = [1, 2, 3, 4, 5]
assert A[:1] != 1
assert A[:1] == [1]
assert A[1:] == [2, 3, 4, 5]
assert A[1:3] == [2, 3] # limit 3 not included
assert A[-1] == 5
assert A[-1:] == [5] # last
print('Tests passed')
Append
p168 You can append the list.
"""List append() extend()
To add an element to a list use append()
To add a list to another list use extend()
The del statement removes values at the index in a list
"""
A = ['a', 'b', 'c']
A.append('x')
assert A != ['a', 'b', 'c']
assert A == ['a', 'b', 'c', 'x']
B = ['d', 'e']
A.extend(B)
assert A != ['a', 'b', 'c']
assert A == ['a', 'b', 'c', 'x', 'd', 'e']
del A[3]
assert A != ['a', 'b', 'c', 'x', 'd', 'e']
assert A == ['a', 'b', 'c', 'd', 'e']
print('Tests passed')
Sorted
Display a sorted list of installed python modules.
"""Display all installed python modules
CLI Examples:
pip list
pip list --outdated
pip show pyperclip
pip install pyperclip
"""
import pkg_resources
pkgs = pkg_resources.working_set
pkgs = sorted(['%s \t %s' % (k.key, k.version) for k in pkgs])
print('\n'.join(pkgs))
# ...
# ufw 0.36
# unattended-upgrades 0.1
# urllib3 1.25.8
➥ Questions