Tuples can be concatenated with the + operator,
>>> CreepyCrawlies
('spiders', 'ants', 'lizards')
>>> pasta
('macaroni', 'spaghetti', 'lasagne', 'fettucine')
>>> strangeFood = CreepyCrawlies + pasta
>>> strangeFood
('spiders', 'ants', 'lizards', 'macaroni', 'spaghetti', 'lasagne',
'fettucine')
>>>
and repeated with the * operator.
>>> pasta * 5
('macaroni', 'spaghetti', 'lasagne', 'fettucine', 'macaroni', 'spaghetti',
'lasagne', 'fettucine', 'macaroni', 'spaghetti', 'lasagne', 'fettucine',
'macaroni',
'spaghetti', 'lasagne', 'fettucine', 'macaroni', 'spaghetti', 'lasagne',
'fettucine')
>>>
"Slices" of a tuple can be extracted using notation similar
to that used with lists - take a look:
>>> pasta = ("macaroni", "spaghetti", "lasagne", "fettucine",
"tagliatelle", "rigatoni")
>>> pasta[0]
'macaroni'
>>> pasta[2:]
('lasagne', 'fettucine', 'tagliatelle', 'rigatoni')
>>> pasta[1:3]
('spaghetti', 'lasagne')
>>> pasta[:4]
('macaroni', 'spaghetti', 'lasagne', 'fettucine')
>>> pasta[-4]
'lasagne'
>>> pasta[-1]
'rigatoni'
>>>
The built-in len() function can be used to calculate the
number of elements in a tuple,
>>> pasta
('macaroni', 'spaghetti', 'lasagne', 'fettucine', 'tagliatelle', 'rigatoni')
>>> len(pasta)
6
>>>
while the "in" and "not in" operators can be used to test for
the presence of a particular element in a tuple. A match returns 1 (true), while a failure returns 0 (false).
>>> pasta
('macaroni', 'spaghetti', 'lasagne', 'fettucine', 'tagliatelle', 'rigatoni')
>>> "macaroni" in pasta
1
>>> "ravioli" in pasta
0
>>> "ravioli" not in pasta
1
>>> "ravio" not in pasta
1
>>> "maca" in pasta
0
>>>
Please enable JavaScript to view the comments powered by Disqus. blog comments powered by