Learning Python: Tuples
Tuples are another data structure available in Python. Tuples give us the ability to create objects that are immutable.
One of the differences between tuples and lists, are that Tuples use round brackets while lists use square brackets.
A simple tuple
name_dept = ("Peter", "Engineering")
We can access a tuple like a list using its index:
print(name_dept) # "Peter" print(name_dept) # "Engineering"
We can use the
print(name_dept.index('Peter')) # 0 print(name_dept.index('Engineering')) # 1
We can search tuples from the end like we can with lists:
name_dept[-1] # True
We can check if an element is in a tuple:
print("Peter" in name_dept) # True
We can get the length of a tuple using the
len(name_dept) # 2
Part of a tuple can be extracted by slicing:
name_dept[0:2] # ('Peter', 'Engineering') name_dept[1:] # ('Engineering')
A new tuple can be created from an existing tuple:
tuple1 = name_dept + ("Kelly", "IT")
This blog post was originally published on my blog Communicode, where I write about different tech topics.