Skip to content

Commit 23f486d

Browse files
committed
Initial commit of item_05
1 parent f80cde1 commit 23f486d

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed

item_05.py

+98
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
#!/usr/bin/env python3
2+
3+
'''Item 5 from Effective Python'''
4+
5+
import logging
6+
from pprint import pprint
7+
from sys import stdout as STDOUT
8+
9+
10+
# Example 1
11+
print('Example 1:\n==========')
12+
a = [
13+
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
14+
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
15+
]
16+
print('First four:', a[:4])
17+
print('Last four: ', a[-4:])
18+
print('Middle two:', a[3:-3])
19+
20+
21+
# Example 2
22+
assert a[:5] == a[0:5]
23+
24+
25+
# Example 3
26+
assert a[5:] == a[5:len(a)]
27+
28+
29+
# Example 4
30+
print('\nExample 4:\n==========')
31+
print(a[:5])
32+
print(a[:-1])
33+
print(a[4:])
34+
print(a[-3:])
35+
print(a[2:5])
36+
print(a[2:-1])
37+
print(a[-3:-1])
38+
39+
40+
# Example 5
41+
a[:] # ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
42+
a[:5] # ['a', 'b', 'c', 'd', 'e']
43+
a[:-1] # ['a', 'b', 'c', 'd', 'e', 'f', 'g']
44+
a[4:] # ['e', 'f', 'g', 'h']
45+
a[-3:] # ['f', 'g', 'h']
46+
a[2:5] # ['c', 'd', 'e']
47+
a[2:-1] # ['c', 'd', 'e', 'f', 'g']
48+
a[-3:-1] # ['f', 'g']
49+
50+
51+
# Example 6
52+
print('\nExample 6:\n==========')
53+
first_twenty_items = a[:20]
54+
last_twenty_items= a[-20:]
55+
print('First twenty items: %s' % first_twenty_items)
56+
print('Last twenty items: %s' % last_twenty_items)
57+
58+
59+
# Example 7
60+
print('\nExample 7:\n==========')
61+
try:
62+
a[20]
63+
except:
64+
logging.exception('Expected')
65+
else:
66+
print('a[20] is: %s' % a[20])
67+
68+
69+
# Example 8
70+
print('\nExample 8:\n==========')
71+
b = a[4:]
72+
print('Before: ', b)
73+
b[1] = 99
74+
print('After: ', b)
75+
print('No change: ', a)
76+
77+
78+
# Example 9
79+
print('\nExample 9:\n==========')
80+
print('Before ', a)
81+
a[2:7] = [99, 22, 14]
82+
print('After ', a)
83+
84+
85+
# Example 10
86+
print('\nExample 10:\n==========')
87+
b = a[:]
88+
assert b == a and b is not a
89+
print(b)
90+
91+
92+
# Example 11
93+
print('\nExample 11:\n==========')
94+
b = a
95+
print('Before', a)
96+
a[:] = [101, 102, 103]
97+
assert a is b # Still the same list object
98+
print('After ', a) # Now has different contents

0 commit comments

Comments
 (0)