@@ -8,7 +8,7 @@ Comprehensive Python Cheatsheet
8
8
9
9
Contents
10
10
--------
11
- **   ;  ;  ; ** ** 1. Collections:** **   ; ** ** [ ` List ` ] ( #list ) ** __ ,__ ** [ ` Dict ` ] ( #dictionary ) ** __ ,__ ** [ ` Set ` ] ( #set ) ** __ ,__ ** [ ` Range ` ] ( #range ) ** __ ,__ ** [ ` Enumerate ` ] ( #enumerate ) ** __ ,__ ** [ ` Namedtuple ` ] ( #named-tuple ) ** __ ,__ ** [ ` Iterator ` ] ( #iterator ) ** __ ,__ ** [ ` Generator ` ] ( #generator ) ** __ .__
11
+ **   ;  ;  ; ** ** 1. Collections:** **   ; ** ** [ ` List ` ] ( #list ) ** __ ,__ ** [ ` Dict ` ] ( #dictionary ) ** __ ,__ ** [ ` Set ` ] ( #set ) ** __ ,__ ** [ ` Tuple ` ] ( #tuple ) ** __ ,__ ** [ ` Range ` ] ( #range ) ** __ ,__ ** [ ` Enumerate ` ] ( #enumerate ) ** __ ,__ ** [ ` Iterator ` ] ( #iterator ) ** __ ,__ ** [ ` Generator ` ] ( #generator ) ** __ .__
12
12
**   ;  ;  ; ** ** 2. Types:** **   ;  ;  ;  ;  ;  ;  ;  ;  ;  ; ** ** [ ` Type ` ] ( #type ) ** __ ,__ ** [ ` String ` ] ( #string ) ** __ ,__ ** [ ` Regex ` ] ( #regex ) ** __ ,__ ** [ ` Format ` ] ( #format ) ** __ ,__ ** [ ` Numbers ` ] ( #numbers ) ** __ ,__ ** [ ` Combinatorics ` ] ( #combinatorics ) ** __ ,__ ** [ ` Datetime ` ] ( #datetime ) ** __ .__
13
13
**   ;  ;  ; ** ** 3. Syntax:** **   ;  ;  ;  ;  ;  ;  ;  ;  ; ** ** [ ` Args ` ] ( #arguments ) ** __ ,__ ** [ ` Inline ` ] ( #inline ) ** __ ,__ ** [ ` Closure ` ] ( #closure ) ** __ ,__ ** [ ` Decorator ` ] ( #decorator ) ** __ ,__ ** [ ` Class ` ] ( #class ) ** __ ,__ ** [ ` Duck_Types ` ] ( #duck-types ) ** __ ,__ ** [ ` Enum ` ] ( #enum ) ** __ ,__ ** [ ` Exceptions ` ] ( #exceptions ) ** __ .__
14
14
**   ;  ;  ; ** ** 4. System:** **   ;  ;  ;  ;  ;  ;  ;  ; ** ** [ ` Print ` ] ( #print ) ** __ ,__ ** [ ` Input ` ] ( #input ) ** __ ,__ ** [ ` Command_Line_Arguments ` ] ( #command-line-arguments ) ** __ ,__ ** [ ` Open ` ] ( #open ) ** __ ,__ ** [ ` Path ` ] ( #path ) ** __ ,__ ** [ ` Command_Execution ` ] ( #command-execution ) ** __ .__
@@ -55,7 +55,8 @@ list_of_chars = list(<str>)
55
55
```
56
56
57
57
``` python
58
- index = < list > .index(< el> ) # Returns first index of item or raises ValueError.
58
+ < bool > = < el> in < collection> # For dictionary it checks if key exists.
59
+ index = < list > .index(< el> ) # Returns index of first occurrence or raises ValueError.
59
60
< list > .insert(index, < el> ) # Inserts item at index and moves the rest to the right.
60
61
< el> = < list > .pop([index]) # Removes and returns item at index or from the end.
61
62
< list > .remove(< el> ) # Removes first occurrence of item or raises ValueError.
@@ -126,13 +127,42 @@ Set
126
127
< set > .discard(< el> ) # Doesn't raise an error.
127
128
```
128
129
129
- ### Frozenset
130
- #### Is hashable, meaning it can be used as a key in a dictionary or as an element in a set.
130
+ ### Frozen Set
131
+ * ** Is immutable and hashable.**
132
+ * ** That means it can be used as a key in a dictionary or as an element in a set.**
131
133
``` python
132
134
< frozenset > = frozenset (< collection> )
133
135
```
134
136
135
137
138
+ Tuple
139
+ -----
140
+ ** Tuple is an immutable and hashable list.**
141
+ ``` python
142
+ < tuple > = ()
143
+ < tuple > = (< el> , )
144
+ < tuple > = (< el_1> , < el_2> , ... )
145
+ ```
146
+
147
+ ### Named Tuple
148
+ ** Tuple's subclass with named elements.**
149
+
150
+ ``` python
151
+ >> > from collections import namedtuple
152
+ >> > Point = namedtuple(' Point' , ' x y' )
153
+ >> > p = Point(1 , y = 2 )
154
+ Point(x = 1 , y = 2 )
155
+ >> > p[0 ]
156
+ 1
157
+ >> > p.x
158
+ 1
159
+ >> > getattr (p, ' y' )
160
+ 2
161
+ >> > p._fields # Or: Point._fields
162
+ (' x' , ' y' )
163
+ ```
164
+
165
+
136
166
Range
137
167
-----
138
168
``` python
@@ -155,27 +185,6 @@ for i, el in enumerate(<collection> [, i_start]):
155
185
```
156
186
157
187
158
- Named Tuple
159
- -----------
160
- * ** Tuple is an immutable and hashable list.**
161
- * ** Named tuple is its subclass with named elements.**
162
-
163
- ``` python
164
- >> > from collections import namedtuple
165
- >> > Point = namedtuple(' Point' , ' x y' )
166
- >> > p = Point(1 , y = 2 )
167
- Point(x = 1 , y = 2 )
168
- >> > p[0 ]
169
- 1
170
- >> > p.x
171
- 1
172
- >> > getattr (p, ' y' )
173
- 2
174
- >> > p._fields # Or: Point._fields
175
- (' x' , ' y' )
176
- ```
177
-
178
-
179
188
Iterator
180
189
--------
181
190
``` python
@@ -250,15 +259,36 @@ from types import FunctionType, MethodType, LambdaType, GeneratorType
250
259
** An abstract base class introduces virtual subclasses, that don’t inherit from it but are still recognized by isinstance() and issubclass().**
251
260
252
261
``` python
253
- from numbers import Integral, Rational, Real, Complex, Number
254
- from collections.abc import Sequence, Collection, Iterable
262
+ >> > from collections.abc import Sequence, Collection, Iterable
263
+ >> > isinstance ([1 , 2 , 3 ], Iterable)
264
+ True
265
+ ```
266
+
267
+ ``` text
268
+ +------------------+----------+------------+----------+
269
+ | | Sequence | Collection | Iterable |
270
+ +------------------+----------+------------+----------+
271
+ | list, range, str | yes | yes | yes |
272
+ | dict, set | | yes | yes |
273
+ | iter | | | yes |
274
+ +------------------+----------+------------+----------+
255
275
```
256
276
257
277
``` python
278
+ >> > from numbers import Integral, Rational, Real, Complex, Number
258
279
>> > isinstance (123 , Number)
259
280
True
260
- >> > isinstance ([1 , 2 , 3 ], Iterable)
261
- True
281
+ ```
282
+
283
+ ``` text
284
+ +--------------------+----------+----------+------+---------+--------+
285
+ | | Integral | Rational | Real | Complex | Number |
286
+ +--------------------+----------+----------+------+---------+--------+
287
+ | int | yes | yes | yes | yes | yes |
288
+ | fractions.Fraction | | yes | yes | yes | yes |
289
+ | float | | | yes | yes | yes |
290
+ | complex | | | | yes | yes |
291
+ +--------------------+----------+----------+------+---------+--------+
262
292
```
263
293
264
294
@@ -408,18 +438,17 @@ Format
408
438
409
439
Numbers
410
440
-------
411
- * ** Int, float and complex are the only number types.**
412
- * ** I use ` <num> ` to mean any of the above and ` <real> ` for either int or float.**
413
-
414
441
``` python
415
- < int > = int (< float / str / bool > ) # Or: math.floor(<float>)
416
- < float > = float (< int / str / bool > )
417
- < complex > = complex (real = 0 , imag = 0 ) # Or: <real> + <real>j
442
+ < int > = int (< float / str / bool > ) # Or: math.floor(<float>)
443
+ < float > = float (< int / str / bool > )
444
+ < complex > = complex (real = 0 , imag = 0 ) # Or: <real> + <real>j
445
+ < Fraction> = fractions.Fraction(numerator = 0 , denominator = 1 )
418
446
```
447
+ * ** ` 'int(<str>)' ` and ` 'float(<str>)' ` raise ValueError on malformed strings.**
419
448
420
449
### Basic Functions
421
450
``` python
422
- < num> = pow (< num> , < num> ) # Or: <num> ** <num>
451
+ < num> = pow (< num> , < num> ) # Or: <num> ** <num>
423
452
< real> = abs (< num> )
424
453
< int > = round (< real> )
425
454
< real> = round (< real> , ±ndigits)
@@ -1027,6 +1056,31 @@ class MyCollection:
1027
1056
yield el
1028
1057
```
1029
1058
1059
+ ``` python
1060
+ >> > from collections.abc import Sequence, Collection, Iterable
1061
+ >> > a = MyCollection([1 , 2 , 3 ])
1062
+ >> > isinstance (a, Sequence), isinstance (a, Collection), isinstance (a, Iterable)
1063
+ (False , True , True )
1064
+ ```
1065
+
1066
+ ### Iterator
1067
+ ``` python
1068
+ class Counter :
1069
+ def __init__ (self ):
1070
+ self .i = 0
1071
+ def __next__ (self ):
1072
+ self .i += 1
1073
+ return self .i
1074
+ def __iter__ (self ):
1075
+ return self
1076
+ ```
1077
+
1078
+ ``` python
1079
+ >> > counter = Counter()
1080
+ >> > next (counter), next (counter), next (counter)
1081
+ (1 , 2 , 3 )
1082
+ ```
1083
+
1030
1084
### Callable
1031
1085
``` python
1032
1086
class Counter :
@@ -1858,33 +1912,19 @@ retention=<int>|<datetime.timedelta>|<str>
1858
1912
1859
1913
Scraping
1860
1914
--------
1915
+ #### Scrapes and prints Python's URL and version number from Wikipedia:
1861
1916
``` python
1862
1917
# $ pip3 install requests beautifulsoup4
1863
- >> > import requests
1864
- >> > from bs4 import BeautifulSoup
1865
- >> > url = ' https://en.wikipedia.org/wiki/Python_(programming_language)'
1866
- >> > page = requests.get(url)
1867
- >> > doc = BeautifulSoup(page.text, ' html.parser' )
1868
- >> > table = doc.find(' table' , class_ = ' infobox vevent' )
1869
- >> > rows = table.find_all(' tr' )
1870
- >> > link = rows[11 ].find(' a' )[' href' ]
1871
- >> > ver = rows[6 ].find(' div' ).text.split()[0 ]
1872
- >> > link, ver
1873
- (' https://www.python.org/' , ' 3.7.2' )
1874
- ```
1875
-
1876
- ### Selenium
1877
- ** Library for scraping dynamically generated web content.**
1878
-
1879
- ``` python
1880
- # $ brew cask install chromedriver
1881
- # $ pip3 install selenium
1882
- >> > from selenium import webdriver
1883
- >> > driver = webdriver.Chrome()
1884
- >> > driver.get(url)
1885
- >> > xpath = ' //*[@id="mw-content-text"]/div/table[1]/tbody/tr[7]/td/div'
1886
- >> > driver.find_element_by_xpath(xpath).text.split()[0 ]
1887
- ' 3.7.2'
1918
+ import requests
1919
+ from bs4 import BeautifulSoup
1920
+ url = ' https://en.wikipedia.org/wiki/Python_(programming_language)'
1921
+ page = requests.get(url)
1922
+ doc = BeautifulSoup(page.text, ' html.parser' )
1923
+ table = doc.find(' table' , class_ = ' infobox vevent' )
1924
+ rows = table.find_all(' tr' )
1925
+ link = rows[11 ].find(' a' )[' href' ]
1926
+ ver = rows[6 ].find(' div' ).text.split()[0 ]
1927
+ print (link, ver)
1888
1928
```
1889
1929
1890
1930
@@ -1996,7 +2036,7 @@ from datetime import datetime
1996
2036
time_str = datetime.now().strftime(' %Y%m%d %H%M%S' )
1997
2037
filename = f ' profile- { time_str} .png '
1998
2038
drawer = output.GraphvizOutput(output_file = filename)
1999
- with PyCallGraph(output = drawer):
2039
+ with PyCallGraph(drawer):
2000
2040
< code_to_be_profiled>
2001
2041
```
2002
2042
0 commit comments