Python 3 Tuples

The tuple data type is almost identical to the list data type, except in two ways.

1) Tuples are typed with parenthesis ( and ) instead of square brackets [ and ]
2) Tuples are immutable, whereas lists are mutable.

Benefit of using tuples:

You can use tuples to convey to anyone reading your code that you don't intend for that sequence of values to change.

If you need an ordered sequence of values that never changes, use a tuple. A second benefit of using tuples instead of lists is that , because they are immutable and their contents don't change. Python can implement some optimizations that make code using tuples slightly faster than code using lists.

E.g. fruits = ('Banana', 'Apple', 'Carrot', 'Strawberry')

If you have only one value in your tuple, you can indicate this by placing a trailing comma after the value inside the parenthesis. Otherwise, Python will think you've just typed a value inside regular parenthesis.

E.g. fruits = ('Banana',)

The comma is what lets python know this is a tuple value.

Converting Types with the list() and tuple() functions:

Just like how str(12) returns '12', the string representation of the number 12, the functions list() and tuple() will return list and tuple versions of the values passed to them.

Converting a tuple to a list is handy if you need a mutable version of a tuple value.

 

Comments

Popular posts from this blog

bb.utils.contains yocto

make config vs oldconfig vs defconfig vs menuconfig vs savedefconfig

PR, PN and PV Variable in Yocto