Tuples in Python

1) What is Tuple?
  • Just like List, Tuple is a collection of ordered elements. But the difference between list and Tuple is, tuples are immutable i.e. the elements in the Tuple cannot be changed, once it is assigned.
  • Tuples also can store both homogeneous and heterogeneous elements.
2) Creating a Tuple
  • Tuples can be created by placing all the elements separated by commas inside parentheses().
  • Parentheses are optional but it is good practice to use them.
     Ex: tup = ( 2, 4, "three")

2.1) Tuple Packing
  • Tuples can also be created without parentheses. This is called Tuple packing.
     Ex:  tup = 2, 4, "three"

  2.2) Creating a Tuple with a single element
  • To create a Tuple with a single element, we have to include a comma at the end of the element (trailing comma) even though it has only one value.
     Ex: tup = (2,)

3) Accessing Tuple elements

3.1) Indexing
  • Since Tuples are ordered, we can access the Tuple elements by referring to the index position of the element, inside square brackets.
  • We can also access the Tuple element from the end using a negative index.
  • In general, negative index means starting from the end, -1 refers to last, -2 refers to second last, and so on.
  • Ex:
Tuple Index Access
Output
3.2) Slicing
  • We can access a range of elements in a Tuple by specifying a range of index [start: end] 
  • The return value of slicing will be a new Tuple with specified elements.
  • We can also specify the negative index if we want to slice the element from the last of the Tuple.
  • Ex:
Tuple index slicing
Output
4) Iterating Tuple elements
  • We can iterate through the Tuple elements by using a for loop.
  • Ex:
Iterating Tuple elements
Output
  • By using the 'in' keyword, we can check whether the element is present in the Tuple or not.
  • Ex:
Searching element in Tuple
Output
5) Changing Tuples
  • Tuples are immutable, unlike List. This means we cannot update or add Tuple elements.
  • Let's see an example and check whether it throws an error or not.
  • Ex:
Changing elements in Tuple
Output
6) Deleting Tuple - del
  • Since Tuples are immutable, we cannot remove elements from them. But we can delete the entire Tuple using the del keyword.
  • Ex:
Deleting Tuple
Output
7) Concatenation/Joining and nesting of two tuples

Concatenation and nesting in Tuple
Output
8) Tuple Methods
  • Python offers two built-in methods that can be used on tuples.
  • count() - returns the number of times the specified value present in the tuple.
  • index() - returns the index position of the specified value where it was found first. If not found, it will throw an error.
Tuple built-in function
Output

No comments:

Post a Comment

You might also like

Deploy your Django web app to Azure Web App using App Service - F1 free plan

In this post, we will look at how we can deploy our Django app using the Microsoft Azure app service - a free plan. You need an Azure accoun...