Search⌘ K
AI Features

The Python Language 2

Tuples and ranges in Python are immutable sequence types, useful for storing heterogeneous sequences and contiguous integers, respectively. Lists serve as mutable counterparts to tuples, allowing for operations like item addition through the + operator. Slicing provides a means to access sequence elements with flexible parameters, including negative indexing. Python dictionaries, defined with curly braces, are mutable structures that map key/value pairs, with keys being immutable. Since Python 3.7, they maintain insertion order. All these sequence types support comparisons and the in keyword for membership testing.

We'll cover the following...

Tuples and ranges

In the previous lesson, we introduced str, which is an immutable sequence type for storing and manipulating strings. Other immutable sequence types are tuple and range. Tuples can be used for storing sequences of any type, and ranges store contiguous sequences of int.

Python 3.5
x = (1, 2, 3, 4) # a tuple is an immutable sequence
y = x[3] # assign the 4th element in the tuple to y
print(y) # print the integer 4
x = range(1,4) # create a range from 1 (inclusive) to 4 (exclusive)
y = tuple(x) # return a new tuple from the range
print(y) # prints (1, 2, 3)
y[1] = 3 # y is immutable this will throw a TypeError exception

Whereas, ranges can also be created ...