Python Tuples

Table Of Contents:

  1. What Is A Tuple?
  2. How To Create A Tuple In Python?
  3. Immutability Nature Of Tuple.
  4. Accessing Tuple Items.
  5. Tuple Membership Test.
  6. Updating A Tuple.
  7. Unpacking A Tuple.
  8. Joining Tuples.
  9. Slicing A Tuple.
  10. Deleting A Tuple.

(1) What Is A Tuple?

  • Tuples are used to store multiple items in a single variable.
  • Tuples can store heterogeneous elements inside them.
  • Tuples keep elements insertion order as it is.
  • Tuples can store duplicate elements inside them.
  • Tuples are immutable in nature, meaning that we cannot change, add or remove items after the tuple has been created.

(2) How To Create A Tuple?

  • Tuples can be created by using parenthesis ( ).
  • The elements of the tuple are separated using a comma ( , ).

Example

tple1 = (1,2,3,4,5) #Storing Integer Values

tple2 = ('a','b','c','d','e') #Storing Character Values

tple3 = (1,'a',2,'b',3,'c',4,'d',5) #Storing Mixed Values

tple4 = (1,1,'a','a',4.58,0.548,'Hello') #Storing Duplicate Values.

print(tple1)

print(tple2)

print(tple3)

print(tple4)
Output:

(1, 2, 3, 4, 5)
('a', 'b', 'c', 'd', 'e')
(1, 'a', 2, 'b', 3, 'c', 4, 'd', 5)
(1, 1, 'a', 'a', 4.58, 0.548, 'Hello')

(3) Immutability Nature Of Tuple.

  • An immutable object can’t be changed after it is created.
  • Whenever a new object is created, a new memory location is assigned to it.
  • Immutability ensures that the memory location is write protected.
  • That means you can not add, remove, or update the variables.
  • int, float, bool, string, Unicode, and tuple are the immutable data types in Python.

Example-1

x = 150

print('Id-',id(x))

x = 200

print('Id-',id(x))
Output:

Id- 1685421792
Id- 1685423392

Note:

  • Here you can see that when you change the same variable ‘x’ it will assign a new memory location to it.
  • Here you can see the different id values :
    Id- 1685421792
    Id- 1685423392

Example-2

tple = (1,2,3,4,5)

print('Id-',id(tple))

tple = (1,2,3,4,5.6,7,8,9,10)

print('Id-',id(tple))
Output:

Id- 1872279234256
Id- 1872278529272

Example-3: Getting Value From Memory Address.

#import ctypes
import ctypes

val = 20

x = id(val)

print("Memory address - ", x)

# get the value through memory address
a = ctypes.cast(x, ctypes.py_object).value

print("Value - ", a)
Output:

Memory address -  1685417632
Value -  20

(4) Accessing Tuple Items.

  • You can access tuple items by referring to the index number, inside square brackets [] .
  • tuple[Start index : End Index : Steps]
  • Start Index: Starting Index value from where you want to start.
  • End Index: Ending Index Value till when you want to go.
  • Steps: Number of steps it will jump from Start Index to End Index.

Example-1

tple = (1,2,3,4,5,6,7,8,9,10)

print(tple[0]) #Get Value At Index 0

print(tple[1]) #Get The Value At Index 1

print(tple[0:5]) #Get The Values From 0 to 5-1 = 4th Index

print(tple[0:10:2]) #Start From 0 End at 10-1 = 9 and Jumps 2 Number Of Steps.
Output:

1
2
(1, 2, 3, 4, 5)
(1, 3, 5, 7, 9)

Example-2: Accessing Using For Loop

tple = (1,2,3,4,5,6,7,8,9,10)

for i in tple:
    print(i)
Output:
1
2
3
4
5
6
7
8
9
10

(5) Tuple Membership Tests.

  • You can check whether an element is present inside a tuple or not by using the ‘in’ and ‘not in’ operators.
  • ‘in’ – Returns True if the element is present inside the Tuple.
  • ‘not in’ – Returns True is the element that is not present inside the Tuple.

Example-1: in Operator

tple = (1,2,3,4,5,6,7,8,9,10)

if 5 in tple:
    print("Element Is Present")
else:
    print("Element Is Not Present")
Output:

Element Is Present

Example-2: not in Operator

tple = (1,2,3,4,5,6,7,8,9,10)

tple = (1,2,3,4,5,6,7,8,9,10)

if 15 not in tple:
    print("Element Is Not Present")
else:
    print("Element Is Present")
Output:

Element Is Not Present

(6) Updating A Tuple

  • Tuples are unchangeable, meaning that you cannot change, add, or remove items once the tuple is created.
  • But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.

Example-1:

x = ("apple", "banana", "cherry")

y = list(x) #Converting Tuple Into A List.

y[1] = "kiwi"

x = tuple(y) #Converting Back List To Tuple.

print(x)
Output:

('apple', 'kiwi', 'cherry')

Note:

  • Note that here you are actually not changing the original value of ‘x’.
  • When you update the value it will create a new memory location and assign the values.
  • Before and after the update the id’s will be different,
    Id- 1872277592968
    Id- 1872279427256

(7) Unpacking A Tuple

  • When we create a tuple, we normally assign values to it. This is called “packing” a tuple.
  • But, in Python, we are also allowed to extract the values back into variables. This is called “unpacking”.

Example-1: Packing A Tuple

fruits = ("Orange", "Leamon", "Banana")

print(fruits)
Output:

('Orange', 'Leamon', 'Banana')

Note:

  • Here you are packing all the values into a single variable.
  • This is called Tuple packing.

Example-2: Unpacking A Tuple

fruits = ("Orange", "Leamon", "Banana")

(green, yellow, red) = fruits

print(green)
print(yellow)
print(red)
Output:

Orange
Leamon
Banana

(8) Joining A Tuple

  • To join two or more tuples you can use the + operator.
  • It will create a single Tuple with both the Tuple elements.

Example-1: Tuple Addition

tple1 = (1,2,3,4,5)

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

joined = tple1 + tple2

print('Joined Tuple: ',joined)
Output

Joined Tuple:  (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

Example-2: Tuple Multiplication

fruits = ("Orange", "Leamon", "Banana")

doubled = fruits * 2

print(doubled)
Output

('Orange', 'Leamon', 'Banana', 'Orange', 'Leamon', 'Banana')

(9) Slicing A Tuple

  • If you want to retrieve a range of elements from a tuple object you can use the slice operation.
  • Slicing is done using the below syntax.
  • tuple[Start Index : End Index : Steps]
  • Start Index: Starting Index value from where you want to start.
  • End Index: Ending Index Value till when you want to go.
  • Steps: Number of steps it will jump from Start Index to End Index.

Example

tple = (1,2,3,4,5,6,7,8,9,10)

print(tple[0]) #Get Value At Index 0

print(tple[1]) #Get The Value At Index 1

print(tple[0:5]) #Get The Values From 0 to 5-1 = 4th Index

print(tple[0:10:2]) #Start From 0 End at 10-1 = 9 and Jumps 2 Number Of Steps.
Output:

1
2
(1, 2, 3, 4, 5)
(1, 3, 5, 7, 9)

(10) Deleating A Tuple

  • As discussed above, we cannot change the elements in a tuple. It means that we cannot delete or remove items from a tuple.
  • Deleting a tuple entirely, however, is possible using the keyword del.

Example-1

tple = (1,2,3,4,5,6,7,8,9,10)

del tple[4]
Output:

TypeError                                 Traceback (most recent call last)
<ipython-input-91-ad788f5e311e> in <module>()
      1 tple = (1,2,3,4,5,6,7,8,9,10)
      2 
----> 3 del tple[4]

TypeError: 'tuple' object doesn't support item deletion

Note:

  • You can not delete a single element from the Tuple.
  • It will through you an error.

Example-2

tple = (1,2,3,4,5,6,7,8,9,10)

del tple

print(tple)
Output:

NameError                                 Traceback (most recent call last)
<ipython-input-92-ffb54b2c5cee> in <module>()
      3 del tple
      4 
----> 5 print(tple)

NameError: name 'tple' is not defined

Note:

  • After you delete the tuple from memory, you will not be able to access it.
  • It will through you an error.

Leave a Reply

Your email address will not be published. Required fields are marked *