Python Tuples :

Tuples are immutable :

A tuple is a sequence of values. The values can be any type, and they are indexed by integers, so in that respect tuples are a lot like lists. The important difference is that tuples are immutable as well as a tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets. For example : ("ayan","dev","apu","symul")

Creating and Accessing Values in Tuples :

Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these comma-separated values between parentheses also. To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index.

Example :

  1. newtuple=("ayan","dev","apu","symul")
  2. print(newtuple) #print full tuple
  3. print(newtuple[1]) #print/return the item in position 1 (start with 0)
  4. input()

Output :

python tuples creating

Note : Once a tuple is created, you cannot change its values. Tuples are unchangeable.

Loop Through a Tuple :

You can loop through the tuple items by using a for loop.

Example :

  1. newtuple=("ayan","dev","apu","symul")
  2. for x in newtuple: print(x) #print the values one by one
  3. input()

Output :

python tuples through for loop

Check if Item Exists :

To determine if a specified item is present in a tuple use the in keyword.

Example :

  1. newtuple=("ayan","dev","apu","symul")
  2. if "dev" in newtuple:
  3. print("Yes, 'dev' is in the tuple") #Check if "dev" is present in the tuple
  4. input()

Output :

python tuples through if statement

Tuples with methods :

python list have built-in methods, methods help us to manipulate tuple items.

Example :

  1. newtuple=("ayan","dev","apu","symul")
  2. print(len(newtuple)) #Print the number of items in the tuple
  3. print(max(newtuple)) #Returns item from the tuple with max value
  4. print(min(newtuple)) #Returns item from the tuple with min value.
  5. input()

Output :

python tuple methods

Tuples methods :

Python includes many built-in methods but here we just adding some of the following built-in methods to manipulate tuples :

  • The len() method determine how many items a list has.
  • The max() method returns item from the tuple with max value.
  • The min() method returns item from the tuple with min value.
  • The count() method returns the number of times a specified value occurs in a tuple.
  • The index() method searches the tuple for a specified value and returns the position of where it was found.

Computer Science Engineering

Special Notes

It's a special area where you can find special questions and answers for CSE students or IT professionals. Also, In this section, we try to explain a topic in a very deep way.

CSE Notes