11# Handy data types in the standard library
22
3- [ ] (this doesn't explain how dict.setdefault and collections.defaultdict
4- work because they're not as simple as the things that are here and i
3+ [ ] (this doesn't explain how dict.setdefault and collections.defaultdict
4+ work because they're not as simple as the things that are here and i
55 don't actually use them that much)
66
7- Now we know how to ues lists, tuples and dictionaries. They are commonly
8- used data types in Python, and there's nothing wrong with them. In this
9- chapter we'll learn more data types that make some things easier. You
10- can always do everything with lists and dictionaries, but these data
7+ Now we know how to ues lists, tuples and dictionaries. They are commonly
8+ used data types in Python, and there's nothing wrong with them. In this
9+ chapter we'll learn more data types that make some things easier. You
10+ can always do everything with lists and dictionaries, but these data
1111types can do a lot of the work for you.
1212
1313> If it looks like a duck and quacks like a duck, it must be a duck.
1414
15- Many things in this tutorial are not really something but they behave
16- like something. For example, we'll learn about many things that behave
17- like dictionaries. They are not dictionaries, but we can use them just
18- like if they were dictionaries. This programming style is known as
15+ Many things in this tutorial are not really something but they behave
16+ like something. For example, we'll learn about many things that behave
17+ like dictionaries. They are not dictionaries, but we can use them just
18+ like if they were dictionaries. This programming style is known as
1919** duck-typing** .
2020
2121## Sets
2222
23- Let's say we have a program that keeps track of peoples' names. We can
24- store the names in [ a list] ( ../basics/lists.md ) , and adding a new name
25- is easy as appending to that list. Lists remember their order and it's
23+ Let's say we have a program that keeps track of peoples' names. We can
24+ store the names in [ a list] ( ../basics/lists.md ) , and adding a new name
25+ is easy as appending to that list. Lists remember their order and it's
2626possible to add the same thing multiple times.
2727
2828``` python
@@ -31,15 +31,15 @@ possible to add the same thing multiple times.
3131>> > names.append(' Akuli' )
3232>> > names
3333[' wub_wub' , ' theelous3' , ' RubyPinch' , ' go|dfish' , ' Nitori' , ' Akuli' , ' Akuli' ]
34- >> >
34+ >> >
3535```
3636
37- This is usually what we need, but sometimes it's not. Sometimes we just
38- want to store a bunch of things. We don't need to have the same thing
37+ This is usually what we need, but sometimes it's not. Sometimes we just
38+ want to store a bunch of things. We don't need to have the same thing
3939twice and we don't care about the order.
4040
41- This is when sets come in. They are like lists without order or
42- duplicates, or keys of [ dictionaries] ( ../basics/dicts.md ) without the
41+ This is when sets come in. They are like lists without order or
42+ duplicates, or keys of [ dictionaries] ( ../basics/dicts.md ) without the
4343values. We can create a set just like a dictionary, but without ` : ` .
4444
4545``` python
5353>> >
5454```
5555
56- We can also convert anything [ iterable] ( ../basics/loops.md#summary ) to a
57- set [ by calling the
58- class] ( ../basics/classes.md#why-should-I-use-custom-classes-in-my-projects ) .
56+ We can also convert anything [ iterable] ( ../basics/loops.md#summary ) to a
57+ set [ by calling the
58+ class] ( ../basics/classes.md#why-should-I-use-custom-classes-in-my-projects ) .
5959
6060``` python
6161>> > set (' hello' )
6262{' o' , ' e' , ' h' , ' l' }
6363>> > type (set (' hello' ))
6464< class ' set' >
65- >> >
65+ >> >
6666```
6767
68- When we did ` set('hello') ` we lost one ` h ` and the set ended up in a
69- different order because sets don't contain duplicates or keep track of
68+ When we did ` set('hello') ` we lost one ` h ` and the set ended up in a
69+ different order because sets don't contain duplicates or keep track of
7070their order.
7171
72- Note that ` {} ` is a dictionary because dictionaries are used more often
72+ Note that ` {} ` is a dictionary because dictionaries are used more often
7373than sets, so we need ` set() ` if we want to create an empty set.
7474
7575``` python
@@ -84,7 +84,7 @@ than sets, so we need `set()` if we want to create an empty set.
8484>> >
8585```
8686
87- Sets have a ` remove ` method just like lists have, but they have an ` add `
87+ Sets have a ` remove ` method just like lists have, but they have an ` add `
8888method instead of ` append ` .
8989
9090``` python
@@ -98,24 +98,24 @@ method instead of `append`.
9898>> >
9999```
100100
101- That's the boring part. Now let's have a look at some really handy
101+ That's the boring part. Now let's have a look at some really handy
102102things we can do with sets:
103103
104104``` python
105105>> > a = {' RubyPinch' , ' theelous3' , ' go|dfish' }
106106>> > b = {' theelous3' , ' Nitori' }
107107>> > a & b # names in a and b
108108{' theelous3' }
109- >> > a | b # names in a, b or both
109+ >> > a | b # names in a, b or both
110110{' Nitori' , ' theelous3' , ' go|dfish' , ' RubyPinch' }
111111>> > a ^ b # names in a or b, but not both
112112{' RubyPinch' , ' Nitori' , ' go|dfish' }
113- >> >
113+ >> >
114114```
115115
116116## Named tuples
117117
118- It can be tempting to make a class that just contains a bunch of data
118+ It can be tempting to make a class that just contains a bunch of data
119119and that's it.
120120
121121``` python
@@ -130,16 +130,16 @@ class Website:
130130github = Website(' https://github.com/' , 2008 , True )
131131```
132132
133- You should avoid making classes like this. This class has only one
134- method, so it doesn't really need to be a class. We could just use a
133+ You should avoid making classes like this. This class has only one
134+ method, so it doesn't really need to be a class. We could just use a
135135tuple instead:
136136
137137``` python
138138github = (' https://github.com/' , 2008 , True )
139139```
140140
141- The problem with this is that if someone reading our code sees something
142- like ` website[1] > 2010 ` it doesn't make much sense, like
141+ The problem with this is that if someone reading our code sees something
142+ like ` website[1] > 2010 ` it doesn't make much sense, like
143143` website.founding_year > 2010 ` would.
144144
145145In cases like this, ` collections.namedtuple ` is handy:
@@ -151,7 +151,7 @@ In cases like this, `collections.namedtuple` is handy:
1511512008
152152>> > for thing in github:
153153... print (thing)
154- ...
154+ ...
155155https:// github.com/
1561562008
157157True
@@ -162,13 +162,13 @@ Website(url='https://github.com/', founding_year=2008, free_to_use=True)
162162>> >
163163```
164164
165- As you can see, our ` github ` behaves like a tuple, but things like
166- ` github.founding_year ` also work and ` github ` looks nice when we have a
165+ As you can see, our ` github ` behaves like a tuple, but things like
166+ ` github.founding_year ` also work and ` github ` looks nice when we have a
167167look at it on the ` >>> ` prompt.
168168
169169## Deques
170170
171- To understand deques, we need to first learn about a list method I
171+ To understand deques, we need to first learn about a list method I
172172haven't talked about earlier. It's called ` pop ` and it works like this:
173173
174174``` python
@@ -186,14 +186,14 @@ haven't talked about earlier. It's called `pop` and it works like this:
186186>> >
187187```
188188
189- The list shortens from the end by one when we pop from it, and we also
190- get the removed item back. So we can add an item to the end of a list
189+ The list shortens from the end by one when we pop from it, and we also
190+ get the removed item back. So we can add an item to the end of a list
191191using ` append ` , and we can remove an item from the end using ` pop ` .
192192
193- It's also possible to do these things in the beginning of a list, but
194- lists were not designed to be used that way and it would be slow if our
195- list would be big. The ` collections.deque ` class makes appending and
196- popping from both ends easy and fast. It works just like lists, but it
193+ It's also possible to do these things in the beginning of a list, but
194+ lists were not designed to be used that way and it would be slow if our
195+ list would be big. The ` collections.deque ` class makes appending and
196+ popping from both ends easy and fast. It works just like lists, but it
197197also has ` appendleft ` and ` popleft ` methods.
198198
199199``` python
@@ -210,18 +210,18 @@ deque(['wub_wub', 'theelous3', 'Nitori', 'RubyPinch', 'go|dfish'])
210210' go|dfish'
211211>> > names
212212deque([' theelous3' , ' Nitori' , ' RubyPinch' ])
213- >> >
213+ >> >
214214```
215215
216- The deque behaves a lot like lists do, and we can do ` list(names) ` if we
216+ The deque behaves a lot like lists do, and we can do ` list(names) ` if we
217217need a list instead of a deque for some reason.
218218
219- Deques are often used as queues. It means that items are always added to
219+ Deques are often used as queues. It means that items are always added to
220220one end and popped from the other end.
221221
222222## Counting things
223223
224- Back in [ the dictionary chapter] ( ../basics/dicts.md#examples ) we learned
224+ Back in [ the dictionary chapter] ( ../basics/dicts.md#examples ) we learned
225225to count the number of words in a sentence like this:
226226
227227``` python
@@ -234,9 +234,9 @@ for word in sentence.split():
234234 counts[word] = 1
235235```
236236
237- This code works just fine, but there are easier ways to do this. For
238- example, we could use the ` get ` method. It works so that
239- ` the_dict.get('hi', 'hello') ` tries to give us ` the_dict['hi'] ` but
237+ This code works just fine, but there are easier ways to do this. For
238+ example, we could use the ` get ` method. It works so that
239+ ` the_dict.get('hi', 'hello') ` tries to give us ` the_dict['hi'] ` but
240240gives us ` 'hello' ` instead if ` 'hi' ` is not in the dictionary.
241241
242242``` python
@@ -257,8 +257,8 @@ for word in sentence.split():
257257 counts[word] = counts.get(word, 0 ) + 1
258258```
259259
260- Counting things like this is actually so common that there's [ a
261- class] ( ../basics/classes.md ) just for that. It's called
260+ Counting things like this is actually so common that there's [ a
261+ class] ( ../basics/classes.md ) just for that. It's called
262262` collections.Counter ` and it works like this:
263263
264264``` python
@@ -267,25 +267,25 @@ class](../basics/classes.md) just for that. It's called
267267>> > counts = collections.Counter(words)
268268>> > counts
269269Counter({' test' : 2 , ' hello' : 2 , ' is' : 1 , ' this' : 1 , ' there' : 1 , ' a' : 1 })
270- >> >
270+ >> >
271271```
272272
273- Now ` counts ` is a Counter object. It behaves a lot like a dictionary,
274- and everything that works with a dictionary should also work with a
275- counter. We can also convert the counter to a dictionary by doing
273+ Now ` counts ` is a Counter object. It behaves a lot like a dictionary,
274+ and everything that works with a dictionary should also work with a
275+ counter. We can also convert the counter to a dictionary by doing
276276` dict(the_counter) ` if something doesn't work with a counter.
277277
278278``` python
279279>> > for word, count in counts.items():
280280... print (word, count)
281- ...
281+ ...
282282test 2
283283is 1
284284this 1
285285there 1
286286a 1
287287hello 2
288- >> >
288+ >> >
289289```
290290
291291## Combining dictionaries
@@ -301,7 +301,7 @@ We can add together strings, lists, tuples and sets easily.
301301(1 , 2 , 3 , 4 , 5 )
302302>> > {1 , 2 , 3 } | {4 , 5 }
303303{1 , 2 , 3 , 4 , 5 }
304- >> >
304+ >> >
305305```
306306
307307But how about dictionaries? They can't be added together with ` + ` .
@@ -311,10 +311,10 @@ But how about dictionaries? They can't be added together with `+`.
311311Traceback (most recent call last):
312312 File " <stdin>" , line 1 , in < module>
313313TypeError : unsupported operand type (s) for + : ' dict' and ' dict'
314- >> >
314+ >> >
315315```
316316
317- Dictionaries have an `update` method that adds everything from another
317+ Dictionaries have an `update` method that adds everything from another
318318dictionary into it. So we can merge dictionaries like this:
319319
320320```python
@@ -323,7 +323,7 @@ dictionary into it. So we can merge dictionaries like this:
323323>> > merged.update({' c' : 3 })
324324>> > merged
325325{' c' : 3 , ' b' : 2 , ' a' : 1 }
326- >> >
326+ >> >
327327```
328328
329329Or we can [write a function](../ basics/ defining- functions.md) like this:
@@ -340,8 +340,8 @@ Or we can [write a function](../basics/defining-functions.md) like this:
340340>> >
341341```
342342
343- Kind of like counting things, merging dictionaries is also a commonly
344- needed thing and there' s a class just for it in the `collections`
343+ Kind of like counting things, merging dictionaries is also a commonly
344+ needed thing and there' s a class just for it in the `collections`
345345module. It' s called ChainMap:
346346
347347```python
@@ -352,36 +352,47 @@ ChainMap({'b': 2, 'a': 1}, {'c': 3})
352352>> >
353353```
354354
355- Our `merged` is kind of like the Counter object we created earlier. It' s
355+ Our `merged` is kind of like the Counter object we created earlier. It' s
356356not a dictionary, but it behaves like a dictionary.
357357
358358```python
359359>> > for key, value in merged.items():
360360... print (key, value)
361- ...
361+ ...
362362c 3
363363b 2
364364a 1
365365>> > dict (merged)
366366{' c' : 3 , ' b' : 2 , ' a' : 1 }
367- >> >
367+ >> >
368368```
369369
370- Starting with Python 3.5 it' s possible to merge dictionaries like this.
371- ** Don' t do this unless you are sure that no-one will need to run your
370+ Starting with Python 3.5 it' s possible to merge dictionaries like this.
371+ ** Don' t do this unless you are sure that no-one will need to run your
372372code on Python versions older than 3.5 .**
373373
374374```python
375375>> > first = {' a' : 1 , ' b' : 2 }
376376>> > second = {' c' : 3 , ' d' : 4 }
377377>> > {** first, ** second}
378378{' d' : 4 , ' c' : 3 , ' a' : 1 , ' b' : 2 }
379- >> >
379+ >> >
380380```
381381
382382# # Summary
383383
384- - Duck typing means requiring some behavior instead of some type . For
385- example, instead of making a function that takes a list we could make
384+ - Duck typing means requiring some behavior instead of some type . For
385+ example, instead of making a function that takes a list we could make
386386 a function that takes anything [iterable](../ basics/ loops.md# summary).
387387- Sets and the collections module are handy. Use them.
388+
389+ ** *
390+
391+ If you like this tutorial, please [give it a
392+ star](../ README .md# how-can-i-thank-you-for-writing-and-sharing-this-tutorial).
393+
394+ You may use this tutorial freely at your own risk. See
395+ [LICENSE ](../ LICENSE ).
396+
397+ [Previous](../ basics/ classes.md) | [Next](functions.md) |
398+ [List of contents](../ README .md# advanced)
0 commit comments