Skip to content

Commit 7bac2b4

Browse files
committed
Update
1 parent 6c1d6f0 commit 7bac2b4

2 files changed

Lines changed: 147 additions & 43 deletions

File tree

python-lib.md

Lines changed: 69 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ Sources:
1515

1616
- [Python built-in
1717
functions](https://docs.python.org/3/library/functions.html)
18+
- [Python lexical
19+
analysis](https://docs.python.org/3/reference/lexical_analysis.html)
1820
- [The Python standard
1921
library](https://docs.python.org/3/library/index.html)
2022

@@ -26,7 +28,7 @@ You might also like these related articles:
2628

2729
-----
2830

29-
## Built-in functions
31+
## Built-in functions and keywords
3032

3133
In general we can categorize built-in functions to:
3234

@@ -43,18 +45,29 @@ In general we can categorize built-in functions to:
4345
- Variable’s scope/location: `locals`, `globals`, `dir`,`id`
4446
- Objects: `callable`, `delattr`, `getattr`, `hasattr`, `setattr`
4547

46-
Python operators also are:
48+
Note that functions require parentheses, for instance `abs(-7)` or
49+
`range(3)`.
4750

48-
- Arithmetic `+`, `-`, `*`, `/`, `**`, `//`, `%`
51+
The most common operators are:
52+
53+
- Arithmetic `+`, `-`, `*`, `/`, `**`, `//`, `%`, `@`
4954
- Indexing: `[`
5055
- Sequence operator: `:`
51-
- Identity: `is`, `is not`
52-
- Logical: `and`, `or`, `not`
53-
- Membership: `in`, `not in`
54-
- Assignment: `=`, `+=`, `-=`, `*=`, `/=`, `**=`, `%=`, `//=`
56+
- Assignment: `=`, `+=`, `-=`, `*=`, `/=`, `**=`, `//=`, `%=`, `@=`
5557
- Ordering and comparison: `<`, `>`, `<=`, `>=`, `==`, `!=`
5658

57-
The following are some examples for the above functions:
59+
The following identifiers are used as reserved words, or keywords of the
60+
language, and cannot be used as ordinary identifier:
61+
62+
False await else import pass
63+
None break except in raise
64+
True class finally is return
65+
and continue for lambda try
66+
as def from nonlocal while
67+
assert del global not with
68+
async elif if or yield
69+
70+
Next are some examples for the above functions:
5871

5972
``` python
6073
divmod(6,4)
@@ -177,6 +190,8 @@ os.remove('<file_name>')
177190
# Env variables
178191
os.getenv('HOME')
179192
## '/home/user'
193+
194+
os.environ ## returns all the envs as ENV:PATH
180195
```
181196

182197
### Unix style pathname pattern expansion (`glob`)
@@ -409,13 +424,56 @@ This module provides various time-related functions.
409424
``` python
410425
import time
411426

412-
time.strftime("%Y-%m-%d %H:%M:%S")
413-
## '2020-08-11 18:17:52'
427+
local_time = time.localtime() # a time tuple expressing local time
428+
local_time
429+
## time.struct_time(tm_year=2021, tm_mon=5, tm_mday=6, tm_hour=22, tm_min=3, tm_sec=32, tm_wday=3, tm_yday=126, tm_isdst=1)
430+
431+
local_time.tm_year
432+
## 2021
433+
434+
time.strftime("%X", local_time) # convert a time tuple to a string according to a format specification
435+
## '22:03:32'
414436

415-
time.strptime("30 Nov 20", "%d %b %y")
437+
time.strftime("%Y-%m-%d %H:%M:%S") # the default tuple is localtime()
438+
## '2021-05-06 22:10:03'
439+
440+
time.time() # return the current time in seconds since the Epoch
441+
## 1620356510.8557692
442+
443+
time.mktime(local_time) # convert a time tuple in local time to seconds since the Epoch
444+
## 1620356612.0
445+
446+
local_time2 = time.localtime()
447+
difference = time.mktime(local_time2) - time.mktime(local_time) # time difference in sec
448+
difference
449+
## 452.0
450+
451+
time.gmtime(difference) # convert seconds since the Epoch to a time tuple
452+
## time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=7, tm_sec=32, tm_wday=3, tm_yday=1, tm_isdst=0)
453+
454+
time.strptime("30 Nov 20", "%d %b %y") # parse a string to a time tuple according to a format specification
416455
## time.struct_time(tm_year=2020, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=335, tm_isdst=-1)
417456
```
418457

458+
Commonly used time format codes:
459+
460+
- `%Y` Year with century as a decimal number.
461+
- `%m` Month as a decimal number \[01,12\].
462+
- `%d` Day of the month as a decimal number \[01,31\].
463+
- `%H` Hour (24-hour clock) as a decimal number \[00,23\].
464+
- `%M` Minute as a decimal number \[00,59\].
465+
- `%S` Second as a decimal number \[00,61\].
466+
- `%z` Time zone offset from UTC.
467+
- `%a` Locale’s abbreviated weekday name.
468+
- `%A` Locale’s full weekday name.
469+
- `%b` Locale’s abbreviated month name.
470+
- `%B` Locale’s full month name.
471+
- `%c` Locale’s appropriate date and time representation.
472+
- `%x` Locale’s appropriate date representation.
473+
- `%X` Locale’s appropriate time representation.
474+
- `%p` Locale’s equivalent of either AM or PM.
475+
- `%I` Hour (12-hour clock) as a decimal number \[01,12\].
476+
419477
### Functions creating iterators for efficient looping (`itertools`)
420478

421479
This module implements a number of iterator building blocks.

python-str.md

Lines changed: 78 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -205,13 +205,22 @@ float('5') + 5
205205
## 10.0
206206

207207
list((2,4,6))
208-
## [2,4,6]
208+
## [2, 4, 6]
209+
210+
list({'a':1,'b':2})
211+
## ['a', 'b']
212+
213+
list({'a':1,'b':2}.values())
214+
## [1, 2]
209215

210216
tuple([1,3,5])
211217
## (1,3,5)
212218

213219
set([1,3,5,1,3,5])
214-
## {1,3,5}
220+
## {1, 3, 5}
221+
222+
dict([('a',1),('b',2),('c',3)])
223+
## {'a': 1, 'b': 2, 'c': 3}
215224
```
216225

217226
-----
@@ -241,20 +250,27 @@ methods for strings:
241250
- `str.lower()` lowercase
242251
- `str.upper()` uppercase
243252
- `str.find(x)` find index of character x
244-
- `str.index(x)` index of x character (similar to `.find(x)` if x is
253+
- `str.index(x)` index of character x (similar to `.find(x)` if x is
245254
in the string)
246255
- `str.count(x)` count how many times x repeated
247256
- `str.replace(x,y)` replace character x with y
248-
- `str.split('sep')` split an string to a list of strings based on the
249-
separator `sep` (can be empty `''`)
250-
- `sep.join(list)` join a list of strings to make an string with
251-
separator `sep` (can be empty `''`) - opposite of `.split()`
252-
- `str.center('chr', num)` see an example in below
257+
- `str.split(x)` split an string to a list of strings based on the
258+
separator x (can be empty `''`)
259+
- `str.join(x)` join list of strings or string x to make an string by
260+
a separator - opposite of `.split()`
261+
- `str.startswith(x)` True if the string starts with x character
262+
- `str.endswith(x)` True if the string ends with x character
263+
- `str.strip()` removing whitespace from the beginning and ending
264+
- `str.center('chr', num)` see an example in the below
253265

254266
For example:
255267

256268
``` python
257269
name = 'python'
270+
271+
name.startswith('p')
272+
## True
273+
258274
name.capitalize()
259275
## 'Python'
260276

@@ -290,16 +306,16 @@ Lists are **mutable**, and their elements are usually **homogeneous**
290306
and are accessed by iterating over the list.
291307

292308
``` python
293-
list_ = [1,3,5,7]
294-
list_[0] = 100 # Lists are mutable
295-
list_
309+
ls = [1,3,5,7]
310+
ls[0] = 100 # Lists are mutable
311+
ls
296312
## [100, 3, 5, 7]
297313

298314
# Lists can hold any type of item
299315
example = [1,True,None,['word',123],'test',(0,1),{'name id': 7}]
300316

301317
# Indexing
302-
list_[1:3]
318+
ls[1:3]
303319
## [3, 5]
304320

305321
example[3][1]
@@ -310,12 +326,14 @@ Here are main lists methods:
310326

311327
- `list.append(x)` append x
312328
- `list.extend(x)` or `+=` extend/add x
313-
- `list.insert(i,x)` insert x in position i
329+
- `list.insert(i,x)` insert x to index i
314330
- `list.remove(x)` remove x
315-
- `list.pop(i)` remove item at position i (similar to `del(list[i])`)
331+
- `list.pop(i)` pop out and remove item at index i (similar to
332+
`del(list[i])`)
333+
- `list.pop()` pop out and remove the last item
316334
- `list.sort()` sort
317335
- `list.reverse()` reverse the order
318-
- `list.count(x)` count number of times x repeated
336+
- `list.count(x)` count number of times x is repeated
319337
- `list.index(x)` find index of item x
320338
- `list.copy()` copy list
321339
- `list.clear()` clear list
@@ -497,7 +515,7 @@ example['first key']
497515
Here are some of dictionaries methods:
498516

499517
- `dict.update()` update/add items
500-
- `dict.popitem()` remove an item
518+
- `dict.popitem()` remove the last item
501519
- `dict.pop(k)` remove item with key k
502520
- `dict.keys()` return keys
503521
- `dict.values()` return values
@@ -559,17 +577,18 @@ production rate of two products, id 23 and id 35, in years 2005 and
559577
2010:
560578

561579
``` python
562-
exmp = [{'id':23,'year':2005,'production':2305},{'id':35,'year':2005,'production':3505},{'id':23,'year':2010,'production':2310},{'id':35,'year':2010,'production':3510}]
580+
production = [{'id':23,'year':2005,'rate':2305},{'id':35,'year':2005,'rate':3505},{'id':23,'year':2010,'rate':2310},{'id':35,'year':2010,'rate':3510}]
563581
```
564582

565583
We can make a dictionary of production rates for each `id_year`
566584
combination such that:
567585

568586
``` python
569-
dict_ = {}
570-
for i in exmp:
571-
dict_['%s_%s' % (i['id'],i['year'])] = i['production']
572-
dict_
587+
annual_rates = {}
588+
for i in production:
589+
annual_rates['%s_%s' % (i['id'],i['year'])] = i['rate']
590+
591+
annual_rates
573592
## {'23_2005': 2305, '35_2005': 3505, '23_2010': 2310, '35_2010': 3510}
574593
```
575594

@@ -579,19 +598,23 @@ of lists such that:
579598

580599
``` python
581600
import collections
582-
dt_ = collections.defaultdict(list)
583-
for i in exmp:
584-
dt_[i['id']].append(i['production'])
585-
dict(dt_)
601+
602+
annual_rates = collections.defaultdict(list)
603+
for i in production:
604+
annual_rates[i['id']].append(i['rate'])
605+
606+
dict(annual_rates)
586607
## {23: [2305, 2310], 35: [3505, 3510]}
587608
```
588609

589610
Now let’s find total production over years:
590611

591612
``` python
592-
for i in dt_:
593-
dt_[i] = sum(dt_[i])
594-
dict(dt_)
613+
annual_rates_total = {}
614+
for i in annual_rates:
615+
annual_rates_total[i] = sum(annual_rates[i])
616+
617+
annual_rates_total
595618
## {23: 4615, 35: 7015}
596619
```
597620

@@ -600,8 +623,8 @@ finite stream of `(key, value)` tuples:
600623

601624
``` python
602625
L = [('Italy', 'Rome'), ('France', 'Paris'), ('US', 'Washington DC')]
603-
dict(iter(L))
604-
{'Italy': 'Rome', 'France': 'Paris', 'US': 'Washington DC'}
626+
dict(L)
627+
## {'Italy': 'Rome', 'France': 'Paris', 'US': 'Washington DC'}
605628
```
606629

607630
### Sets
@@ -633,8 +656,31 @@ for element in [[], (), {}]:
633656
## <class 'dict'>
634657
```
635658

636-
Sets have several methods including set operations such as `union`,
637-
`intersection`, and `difference`.
659+
Sets have several methods including set operations such as:
660+
661+
- `set.add(x)`: add a member to the set
662+
- `set.update(x)`: add a set/list to a set
663+
- `set.remove(x)`: remove a member of the set
664+
- `set.pop()`: pop out and remove the first member
665+
- `set.union(x)`: union of a set/list to a set
666+
- `set.intersection(x)`: intersection of a set/list to a set
667+
- `set.difference(x)`: difference of a set/list to a set
668+
669+
<!-- end list -->
670+
671+
``` python
672+
s = {1,2,3}
673+
t = {3,4,5}
674+
675+
s.union(t)
676+
## {1, 2, 3, 4, 5}
677+
678+
s.intersection(t)
679+
## {3}
680+
681+
s.difference(t)
682+
## {1,2}
683+
```
638684

639685
Iterating through sets:
640686

0 commit comments

Comments
 (0)