Previous Lesson | Table of Contents | Next Lesson |
list
, tuple
, and set
are all classes, yet we never created any of these
collections using the class name as a function to pass in arguments to __init__
,
as we saw back with our Item
class back in Lesson 5:
item = Item(1, "car", 2)
Well, turns out that you can treat those three collections classes the same way
we treated our Item
class. All of the __init__
methods accept a collection
object, whether it be a list
, tuple
, or set
:
s = {1, 2, 3}
l = list(s)
print(l)
This will output:
[1, 2, 3]
Similarly, we can convert list
to set
:
l = [1, 2, 3, 1]
s = set(l)
print(s)
This will output:
{1, 2, 3}
Notice how the duplicate 1
at the end is omitted in this set
. Conversions
between list
and tuple
as well as set
and tuple
behave similarly.
It is this ability to convert between list
, set
, and tuple
that explains
the title of this lesson. Note though that using the class syntax that we see
is only good for converting. If you want to create an actual list
for example
from scratch, you should use the syntax described in the previous lessons,
which for list
you might recall uses brackets.
Finally, it should be noted that although these three classes differ in the details,
there are some things in common amongst all three. A very important one is
that their length can be computed using Python’s len
function:
t = (1, 2, 3)
print(len(t))
This will output:
3
The len
function accepts any collection. Thus, this would not work with an
integer, but it will work with list
, set
, and tuple
. In fact, it will
also work with string
because that is also a collection (of characters).
With that caveat explained, let’s practice what we have learned:
Create a
tuple
with the elements5
,"dog"
, and5
. Then convert thattuple
to aset
. (solution)Output the length of the
tuple
and theset
. (solution)Create a
list
with the elements5
,"dog"
, and5
. Then convert thatlist
to atuple
. (solution)
If you are feeling good about collection conversions, proceed to the next lesson!