\(\renewcommand\AA{\unicode{x212B}}\)
()
,lottery_numbers = (1,2,3,4,5,6)
print(lottery_numbers[0]) # prints 1
print(lottery_numbers[1:3]) # prints (2,3)
# Assignment not allowed
lottery_numbers[3] = 42 # gives error "TypeError: 'tuple' object does not support item assignment"
namedtuple
type. This leads to unambiguous
tuple assignment and creates self-documenting code. For instance, consider a tuple representing a geometric point:from collections import namedtuple
Point = namedtuple('Point', ['x', 'y', 'z'])
p = Point(x=2, y=3, z=4)
print(p.x, p[0]) # elements can be accessed using the field name or by index
from collections import nametuple
will be outlined further on in this tutorial.{}
and can be created empty
or initialized with elements. If initial elements are required then
each key/value pair should be specified using key:value
syntax
and then each separated with a comma, e.g.empty_dict = {} # Empty dictionary my_lookup = {'a' : 1, 'b' : 2} # A dictionary with two keys, each # mapped to the respective value print(my_lookup['b'])
Gives the output:
2
empty_dict['a'] # Results in "KeyError: 'a'"
empty_dict = {} # Empty dictionary
my_lookup = {'a' : 1, 'b' : 2} # A dictionary with two keys
empty_dict['a'] = 1
my_lookup['b'] = 3 # Replaces the value that was referenced by the key 'b' with the new value 3
print(empty_dict['a'], my_lookup['b'])
del
commanddel my_lookup['b'] # Removes the key/value pair with the specified key
my_lookup.clear() # Empties the dictionary
set()
or frozenset()
function. The difference simply corresponding to whether the
structure is marked read-only after creation, where the frozenset
is the read-only structure.set()
function,add()
or
remove()
functions,values = set([1,1,3])
print(values)
values.add(4)
values.remove(1)
print(values)
Gives the output:
set([1, 3])
set([3, 4])
len()
,
x in s
and x not in s
.len()
gives the length of the sequence passed as its argument.x in s
returns True
if x is a member of the sequence s.x not in s
returns True
if x is not a member of the sequence
s.s = [1,2,3,4,5,6] # Also works with all other sequence types
print(len(s))
test = 3 in s
print(test)
test = 7 not in s
print(test)
Gives the output:
6
True
True