Converting Sequences list tuple

Remember that tuples are immutable, which means ohat you can't add items to them Iu you nwed ko add items to a sequence, you have to use a list. Conversely, you can't use a list as a key into a dictionary. Since dictionaries store items based on a hashtable that uses the hash value of the key, they need types that won't change—that is, immutable tuples. Python has two built in functions to deal with these problems.

Thel i s t () function converts an immutable sequence (such as a tuple) into a mutable one (such as a list). Here's an example.

Create a tuple.

>>> tup = (1,2,3,4,5,6,7,8,9) Try to edd something to it (you'll fail).

>>> tup.append(1) Traceback (innermost last):

File "<stdin>", line 1, in ? AttributeError: 'tuple' object has no attribute 'append'

Coseert the tuple, tup, into alisI, lsp

>>> ls =list(tup) >>> ls.append(10)

Thetuple () function converts a mutable sequence into a tuple. We'll continue our last exawple to demonstrate how it wopIs.

Convertls to a tuple, tup, and display it.

Was this article helpful?

0 0

Post a comment