My Python Notes(5)

Python Essentials 1


Tuples

Two tuples, each containing four elements.

A tuple is an immutable sequence type. It can behave like a list, but it can’t be modified in situ.

tuple_1 = (1, 2, 4, 8)
tuple_2 = 1., .5, .25, .125

Each tuple element may be of a different type.

Tupple’s stuff

empty_tuple = ()

single_valaue_tuple = (1,) # the comma is required.


print(empty_tuple)
print(single_valaue_tuple)

The output would be:

()
(1,)


# similar than lists...
my_tuple = (1, 10, 100, 1000)

print(my_tuple[0])
print(my_tuple[-1])
print(my_tuple[1:])
print(my_tuple[:-2])

another_tuple = (1,2,3,4,5.0)

print(another_tuple)

more_tuples = (6, 7, 8, 9, 10)

print(another_tuple * 3)

print(3 in another_tuple)

Variable In a Tuple

var = 123

t1 = (1, )
t2 = (2, )
t3 = (3, var)

t1, t2, t3 = t2, t3, t1

print(t1)
print(t2)
print(t1)
print()
print(t1, t2, t3)

The output will look like:

(2,)
(3, 123)
(2,)

(2,) (3, 123) (1,)

 Share!

 
comments powered by Disqus