Module containers
source code
The following are all instances of container
types.
-
lists
-
tuples
-
strings
-
dictionaries
-
files
What unifies containers is that they contain a well-defined body of
data. Something is either in a container or not.
The in relation is a well-defined test for all
containers:
>>> S = 'abc'
>>> 'b' in S
True
>>> 'd' in S
False
>>> X = [24, 3.14, 'w', 7]
>>> 'w' in X
True
The elements that are 'in' a dictionary are its keys.
>>> D = {'x':42, 'y': 3.14, 'z': 7}
>>> 'x' in D
True
The most common use of in in Python is to define the set
of container elements to be iterated through in a
for-loop:
>>> for e in X:
... print e
...
24
3.14
w
7
>>> for k in D:
... print k
y
x
z
Note there are no guarantees as to which order dictionary keys will be
accessed in. The elements contained in a file are its lines.
>>> file_handle = open('hello.txt','r')
>>> for line in file_handle:
... print line
Hi there!
This is line 2!
But this here is line 3!
>>> file_handle.close()