Skip to content

Commit 27d54ad

Browse files
committed
add tuples, sets and hash tables
1 parent 44ace56 commit 27d54ad

File tree

2 files changed

+109
-0
lines changed

2 files changed

+109
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
.vscode
22
misc
33

4+
NOTES.md
45
TODO.md

README.md

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,31 @@ True
131131
```
132132

133133

134+
## Tuples
135+
```python
136+
>>> t = (1, 2, 'str')
137+
>>> type(t)
138+
<class 'tuple'>
139+
>>> t
140+
(1, 2, 'str')
141+
>>> len(t)
142+
3
143+
144+
>>> t[0] = 10 # Tuples are immutable: `TypeError: 'tuple' object does not support item assignment`
145+
146+
>>> a, b, c = t
147+
>>> a
148+
1
149+
>>> b
150+
2
151+
>>> c
152+
'str'
153+
>>> a, _, _ = t # Get first element and ignore the other two values
154+
>>> a
155+
1
156+
```
157+
158+
134159
## Stacks
135160
```python
136161
>>> stack = []
@@ -204,11 +229,94 @@ True
204229

205230
## Sets
206231
```python
232+
>>> s = set()
233+
>>> s.add(1)
234+
>>> s.add(2)
235+
>>> s
236+
{1, 2}
237+
>>> s.add(1) # Duplicate elements are not allowed
238+
>>> s
239+
{1, 2}
240+
>>> s.add('a') # We can mix types
241+
>>> s
242+
{1, 2, 'a'}
243+
244+
>>> s0 = {1, 2, 'a'}
245+
>>> s0
246+
{1, 2, 'a'}
247+
>>> s1 = set([1, 2, 'a'])
248+
>>> s1
249+
{1, 2, 'a'}
250+
251+
>>> len(s)
252+
3
253+
>>> 'a' in s
254+
True
255+
256+
>>> s.remove(1)
257+
>>> s
258+
{2, 'a'}
259+
>>> s.remove(1) # KeyError: 1
260+
261+
>>> s0 = {1, 2}
262+
>>> s1 = {1, 3}
263+
>>> s0 | s1
264+
{1, 2, 3}
265+
>>> s0.union(s1) # New set will be returned
266+
{1, 2, 3}
267+
268+
>>> s0 = {1, 2}
269+
>>> s1 = {1, 3}
270+
>>> s0 & s1
271+
{1}
272+
>>> s0.intersection(s1) # New set will be returned
273+
{1}
274+
275+
>>> s0 = {1, 2}
276+
>>> s1 = {1, 3}
277+
>>> s0 - s1
278+
{2}
279+
>>> s0.difference(s1)
280+
{2}
207281
```
208282

209283

210284
## Hash Tables
211285
```python
286+
>>> d = {'a': 'hello, world', b: 11}
287+
>>> type(d)
288+
<class 'dict'>
289+
>>> d
290+
{'a': 'hello, world', 'b': 11}
291+
292+
>>> d = dict(a='hello, world', b=11)
293+
294+
>>> d.keys()
295+
dict_keys(['a', 'b'])
296+
>>> d.values()
297+
dict_values(['hello, world', 11])
298+
>>> for k, v in d.items():
299+
... print(k, v)
300+
...
301+
a hello, world
302+
b 11
303+
304+
>>> 'a' in d
305+
True
306+
>>> 1 in d
307+
False
308+
>>> d['a'] += '!'
309+
>>> d
310+
{'a': 'hello, world!', 'b': 11}
311+
>>> d[1] = 'a new element'
312+
>>> d
313+
{'a': 'hello, world!', 'b': 11, 1: 'a new element'}
314+
315+
>>> d[0] += 10 # KeyError: 0
316+
>>> d.get(0, 'a default value') # Return a default value if key does not exist
317+
'a default value'
318+
>>> d.get(1, 'a default value') # Key `1` exists, so the actual value will be returned
319+
'a new element'
212320
```
213321

214322

0 commit comments

Comments
 (0)