Python/Tuples
< Python
Objective![]()
|
LessonThe Python TupleIn Python, a tuple is an immutable sequence. This means that a tuple is similar to a list, except you cannot dynamically modify the tuple itself. Once it's created, it can't be changed or modified. The way the tuple is stored in memory will also be important later on in the course. To create a tuple, you need to create a group of items separated by a comma ( >>> spam = 1, 2, 3
>>> spam
(1, 2, 3)
>>> "A", "B", "C", "D"
('A', 'B', 'C', 'D')
>>> True, False, True, True, False
(True, False, True, True, False)
>>> (1, 3, "G", True)
(1, 3, 'G', True)
>>> bacon = 1,
>>> bacon
(1,)
>>> spam = 1, 2, 3,
>>> spam
(1, 2, 3)
Also note that an empty tuple is simply a pair of parentheses. Tuple IndexingTuples, like lists and strings, follows the same standard for indexing. Indexing starts at 0 for the first item and -1 for the start of the last item. A brief example is shown below. >>> ("A", "B", "C", "D", "E", "F")[0]
'A'
>>> ("A", "B", "C", "D", "E", "F")[1]
'B'
>>> ("A", "B", "C", "D", "E", "F")[-1]
'F'
>>> ("A", "B", "C", "D", "E", "F")[-2]
'E'
Tuple SlicingLike other common sequences, tuples can be sliced. The standard slicing is exactly like slicing taught in previous lessons. A quick example is given below. >>> ("A", "B", "C", "D", "E", "F")[1:]
('B', 'C', 'D', 'E', 'F')
>>> ("A", "B", "C", "D", "E", "F")[:4]
('A', 'B', 'C', 'D')
>>> ("A", "B", "C", "D", "E", "F")[-4:]
('C', 'D', 'E', 'F')
>>> ("A", "B", "C", "D", "E", "F")[0:]
('A', 'B', 'C', 'D', 'E', 'F')
>>> ("A", "B", "C", "D", "E", "F")[0:2]
('A', 'B')
>>> ("A", "B", "C", "D", "E", "F")[11:]
()
>>> ("A", "B", "C", "D", "E", "F")[:-19]
()
>>> ("A", "B", "C", "D", "E", "F")[::]
('A', 'B', 'C', 'D', 'E', 'F')
>>> ("A", "B", "C", "D", "E", "F")[::1]
('A', 'B', 'C', 'D', 'E', 'F')
>>> ("A", "B", "C", "D", "E", "F")[::2]
('A', 'C', 'E')
>>> ("A", "B", "C", "D", "E", "F")[::3]
('A', 'D')
>>> ("A", "B", "C", "D", "E", "F")[::-1]
('F', 'E', 'D', 'C', 'B', 'A')
>>> ("A", "B", "C", "D", "E", "F")[::-2]
('F', 'D', 'B')
>>> ("A", "B", "C", "D", "E", "F")[:3:-1]
('F', 'E')
>>> ("A", "B", "C", "D", "E", "F")[0:4:1]
('A', 'B', 'C', 'D')
>>> ("A", "B", "C", "D", "E", "F")[-2::-1]
('E', 'D', 'C', 'B', 'A')
>>> ("A", "B", "C", "D", "E", "F")[:-19:-1]
('F', 'E', 'D', 'C', 'B', 'A')
>>> ("A", "B", "C", "D", "E", "F")[::11]
('A',)
>>> ("A", "B", "C", "D", "E", "F")[::-56]
('F',)
|
Assignments![]()
|
|