Config Router

  • Google Sheets
  • CCNA Online training
    • CCNA
  • CISCO Lab Guides
    • CCNA Security Lab Manual With Solutions
    • CCNP Route Lab Manual with Solutions
    • CCNP Switch Lab Manual with Solutions
  • Juniper
  • Linux
  • DevOps Tutorials
  • Python Array
You are here: Home / Python / Python Fundamentals – Tuples

Python Fundamentals – Tuples

December 22, 2020 by James Palmer

Python Fundamentals – Tuples

INTRODUCTION

Tuples are very similar to lists, but tuples cannot be changed. That is, a tuple can be viewed as a “constant list”. While lists use square brackets, tuples are written with standard parentheses or no parentheses, and elements are separated with comma as given in the following lists:

 # elements are written without parentheses
 ››› t1 = 'a', 'b', 'c', 'd', 'e'
 # elements written within parentheses
 ››› t2 = ('a' , 'h' , ' c' , 'd' , 'e')
 # a tuple containing a single element or item
 ››› t3 = 'a',
 ››› type(t3)
 ‹type 'tuple'›

a. Syntactically, a tuple is a comma- separated list of values:

››› t1 = 'a' , 'b' , ' c' , 'd' , 'e'

b. Although parentheses is not necessary, it is common to enclose tuples in parentheses:

››› t2 = ('a' , 'b' , ' c', , 'e')

c. To create a tuple with a single element, you have to include a final comma:

››› t3 = 'a', ‹-- note trailing comma

DIFFERENCE BETWEEN LIST AND TUPLE

Differences between lists and tuples are as follows:
(a) Lists are enclosed in square brackets [ ], and their elements and size can be changed, while tuples are enclosed in parentheses () and cannot be updated.
(b) Tuples can be thought of as read-only lists. Tuples protect against accidental changes of their contents, whereas Lists will grow and shrink as needed.
(c) One major feature of tuples is that they are immutable like strings, i.e., you can¬not modify tuples. Lists are mutable; individual items or entire slices can be replaced through assignment statements.

TUPLES ARE IMMUTABLE

Like numbers and strings, tuples are immutable which means you cannot update them or change values of tuple elements. A new object has to be created if a different value has to be stored. You can take portions of an existing tuples to create a new tuples as follows:

 ››› tup1 = (10, 20, 30)
 ››› tup2 = (50, 60, 70)
 ››› tupl (10, 20, 30)
 ››› tup2 (50, 60, 70)
 ››› tup2[0] = 40 # action is not valid for tuples, error will be displayed
 Traceback (most recent call last):
 File "‹pyshell#15›", line 1, in ‹module›
 tup2 [0] = 40
 TypeError: 'tuple' object does not support item assignment So let's create a new 
 tuple as follows:
 ››› tup3 = tupl + tup2
 ››› tup3
 (10, 20, 30, 50, 60, 70)
 ›››

CREATION, INITIALIZATION AND ACCESSING THE ELEMENTS IN A TUPLE

To create a tuple with zero elements, use only the two parentheses For a tuple with one element, use a trailing comma. For a tuple with two or more elements, use a comma between elements. No ending comma is needed.

Tuple Creation
Creating a tuple is as simple as putting different comma-separated values and option¬ally you can put these comma-separated values between parentheses also. For example:

 ››› tup1 = ('C++', 'Python', 1997, 2013)
 ››› tup2 = (1, 2, 3, 4, 5 )
 ››› tup3 = "a", "b", "c", "d"

The empty tuple is written as two parentheses containing nothing:

 # Zero-element tuple
 tup4 = ();
 ››› len(tup4)
 0

To write a tuple containing a single value you have to include a comma, even though there is only one value:

 # One-element tuple
 tup5 = (20,)
 ››› len(tup5)
 1
 # Two-element tuple tup6 = ("one", "two")
 ››› len(tup6)
 2

A tuple in Python is immutable. An immutable object cannot be changed. Once created it always has the same values. On trying to make an item assignment on a tuple will display the following error:

 ››› tup = ('a', 'b', 'd', 'd')
 ››› tup[2] = 'c' # This causes an error h
 Traceback (most recent call last):
 File "‹stdin›", line 1, in ‹module›
 TypeError: 'tuple' object does not support item assignment

Tuple Assignment
You can assign all of the elements in a tuple using a single assignment statement. Tuple assignment occurs in parallel rather than in sequence, making it useful for swapping values.
To swap the values of two variables, with conventional assignment statements, we have to use a temporary variable. For example, to swap a and b:

 temp = a
 a = b
 b = temp

If we have to do this, this becomes cumbersome. Python provides a form of tuple assignment that solves this problem:
a, b = b, a
The left side is a tuple of variables; and the right side is a tuple of values. Each value is assigned to its respective variable. All the expressions on the right side are evaluated before any of the assignments. This feature makes tuple assignment quite versatile.

Accessing Elements in Tuples
To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index. Like string indices, tuple indices start at 0. Accessed items can be either single elements or in groups, known as slices. Subsets can be taken with the slice operator ( [] and [ : ] ) in the same manner as strings. The slice notation in Python uses a colon. On the left side of the colon, we have the starting index. If no starting index is present, the program uses 0. And on the right side of the colon, we have the ending index. If no ending index is present, the last index possible is used.
For example,

 tupl = ('C++', 'Python', 1997, 2013)
 ››› tupl[0]
 C+ +
 ››› tupl[l]
 'Python'

If you want to access value 2013, you can write either tupl[-l] or tupl[3].

 ››› tupl[-1]
 2013
 >>> tupl[3]
 2013

Slices are treated as boundaries and the result will contain all the elements between boundaries.

 ››› tup2 = (1, 2, 3, 4, 5 )
 ››› tup2 [1:5]
 (2, 3, 4, 5)
 ››› tup2 [3:7]
 (4, 5)
 ››› tup2[8]
 Traceback (most recent call last) :
 File "‹pyshell#32›", line 1, in ‹module›
 tup2 [8]
 IndexError: tuple index out of range

Example 1
Program that uses tuple slices.

 values = (1, 3, 5, 7, 9, 11, 13)
 # Copy the tuple
 print(values[:])
 # Copy all values at index 1 or more
 print(values[1:])
 # Copy one value, starting at first
 print(values[:1])
 # Copy values from index 2 to 4
 print(values[2:4])
 RUN
 ›››
 (1, 3, 5, 7, 9, 11, 13)
 (3, 5, 7, 9, 11, 13)
 (1, )
 (5, 7)
 ›››

Figure 18.1 Program that uses tuple slices

The in operator returns whether a given element is contained in a list or tuple:

 ››› 4 in (2, 4, 6, 8)
 True
 ››› 5 in (2, 4, 6, 8)
 False

TUPLE FUNCTIONS

cmp ()
cmp () function compares elements of both tuples. It checks whether the given tuples are same or not. If both are same, it will return 0, otherwise return 1 or -1. If the first tuple is big, then it will return 1, otherwise return -1.
Syntax:

cmp(tupl,tup2) #tupl and tup2 are tuples

Example

 ››› tupl= (11,22,33)
 ››› tup2=(50,60,70)
 ››› tup3=(11,22,33)
 ››› cmp(tupl,tup2) # first tuple is small
 -1
 ››› cmp(tupl,tup3) //same
 0
 ››› cmp(tup2,tupl) //first tuple is big
 1

len()
The method len() returns the number of elements in the tuple.
Syntax:

len(tup)

Example

 ››› tupl= (11,22,33)
 ››› len(tupl)
 3

max() and min()
The max() and min() built-in functions find the largest and smallest elements of a sequence. For strings, the comparison performed is alphabetical, “able” comes before “zero”. So “able” would be less than “zero”. For numbers, the comparison”is numeric, 10 comes before 20. These comparisons are logical.
Syntax:

 max(args) Returns the maximum of a sequence or set of arguments
 min(args) Returns the minimum of a sequence or set of arguments

Example

 ››› max(10,20,30)
 30
 ››› min(10,20,30)
 10

Example 2
Program that uses max() and min() functions.

 # max() and min() for strings
 friends = ("sanjay", "morris", "ajay", "suman")
 print(max(friends))
 print(min(friends))
 # Max and min for numbers
 earnings = (1000, 2020, 500, 400)
 print(max(earnings))
 print(min(earnings))
 RUN
 ›››
 suman
 ajay
 2020
 400
 ›››

Figure 18.2 Program for Example 2

tuple()
It is used to create empty tuple. The empty tuple is written as two parentheses contain¬ing nothing:
Syntax:

t=tuple() #t tuples

Example

 ››› t=tuple()
 ››› print t
 ()

SOLVED EXERCISE

Question 1.
What is tuple?

Answer:
Tuples are a sequence of values of any type, and are indexed by integers. They are immutable. Tuples are enclosed in ().

Question 2.
A tuple in Python is immutable. Comment.

Answer:
A tuple in Python is immutable. An immutable object cannot be changed. Once created it always has the same values.

Question 3.
What is the difference between objects and methods?

Answer:
Strings, lists, and tuples are objects, which means that they not only hold values, but have built-in behaviors called methods, that act on the values in the object.

Question 4.
Is an item assignment on a tuple is possible?

Answer:
No, an assignment statement in tuple is not possible.

Question 5.
Why is len() function used with list and tuple?

Answer:
With lists and tuples, len() function returns the number of elements in the sequence:

››› len(['a', 'b', 'c', 'd'])
4
››› len( (2, 4, 6, 8, 10, 12) )
6

Question 6.
What is the use of in operator?

Answer:
The in operator returns whether a given element is contained in a list or tuple:

››› 4 in (2, 4, 6, 8)
True
››› 5 in (2, 4, 6, 8)
False

Question 7.
Write short note on tuple assignment.

Answer:
An assignment to all of the elements in a tuple is done using a single assignment statement. Tuple assignment occurs in parallel rather than in sequence, making it useful for swapping values.

Question 8.
How will you create tuple with zero element and 1 element?

Answer:
Zero elements: To create a tuple with zero elements, use only the two parentheses “()”
# Zero element tuple
x = ()

One element: For a tuple with one element, use a trailing comma.
# One-element tuple
y = (“sunday”,)

Question 9.
Compare and contrast tuples and list.

Answer:
Tuples are very similar to lists, but tuples cannot be changed, i.e., no changes in the contents of the tuple is allowed. A tuple can be viewed as a ‘constant list’. While lists employ square brackets, tuples are written with standard parentheses or no paren-theses, and elements are separated by comma in lists.

Question 10.
Can we update tuples?

Answer:
Like numbers and strings, tuples are immutable which means you cannot update them or change values of tuple elements.

Question 11.
Differentiate between following two python statement:
››› t1 = ‘a’,
››› t2 = (‘a’)

Answer:
To create a tuple with a single element, you have to include a final comma:
››› t1 = ‘a’,
››› type(tl)
‹type ‘tuple’›

A value in parentheses is not a tuple:
››› t2 = (‘a’)
››› type(t2)
‹type ‘str’›

Question 12.
What is difference between list and tuple?

Answer:
Lists are enclosed in brackets [ ], and their elements and size can be changed, while tuples are enclosed in parentheses () and cannot be updated. Tuples can be thought of as “read-only” lists.

Question 13.
How will you swap values in Python?

Answer:
Python’s “multiple assignment” will swap values in Python:

 # swapping variables in Python
 ››› (x, y) = (1, 2)
 ››› x
 1
 ››› y
 2
 ››› (x, y) = (y, x)
 ››› x
 2
 ››› y
 1

Question 14.
Identify the following are mutable or immutable?
lists, numbers, strings, tuples, and dictionaries.

Answer:
Mutable : lists, dictionaries
Immutable : numbers, strings, tuples

Question 15.
Find the output of the following programs:

(a) ››› numbers = [1, 2, 3, 4]
 ››› [(x, x**2, x**3) for x in numbers]

(b) checks = (10, 20, 30)
 # Add two tuples
 more = checks + checks
 print(more)

(c) checks = (10, 20, 30)
 # Multiply tuple
 total = checks * 3
 print(total)

(d) def test(x):
 # Test x with tuple syntax.
 if x in (0, 2, 4) :
 print("Match")
 else:
 print("No Match")
 test(0)
 test(1)
 test(2)

(e) ››› cmp(1, 2)
 ››› cmp("a", "b")
 ››› cmp(3, 1)
 ››› cmp(3.1, 3.1)

(f) ››› 3* (40+2)
 ››› 3* (40 + 2,)

Answer:
(a) [(1,1,1), (2,4, 8), (3, 9, 27), (4,16, 64)]
(b) (10, 20, 30,10, 20, 30)
(c) (10, 20,30,10, 20, 30,10, 20, 30)
(d) Match x = 0
No Match x = 1
Match x = 2
(e) -1
-1
1
0
(f) 126
(42,42,42)

Multiple choice questions

Question 1.
min() returns:
(a) Largest item in the tuple.
(b) Number of items in the tuple.
(c) Its smallest item in the tuple.
(d) None of these

Answer:
(c)

Question 2.
Tuples cannot be:
(a) Added
(b) Multiplied
(c) Sorted
(d) None of the above

Answer:
(c)

Question 3.
In general, the order of items in a dictionary is
(a) Unpredictable
(b) Predictable
(c) Known
(d) None of these

Answer:
(a)

Question 4.
If we need to create a tuple with a single element, we need to include a final:
(a) Comma
(b) Semicolon
(c) Full stop
(d) None of these

Answer:
(a)

Question 5.
Create empty tuple:
(a) T=tuple[]
(b) T=tuple()
(c) T=tuple{}
(d) None of these

Answer:
(b)

  • Python Fundamentals

Related

Filed Under: Python

Recent Posts

  • How do I give user access to Jenkins?
  • What is docker volume command?
  • What is the date format in Unix?
  • What is the difference between ARG and ENV Docker?
  • What is rsync command Linux?
  • How to Add Music to Snapchat 2021 Android? | How to Search, Add, Share Songs on Snapchat Story?
  • How to Enable Snapchat Notifications for Android & iPhone? | Steps to Turn on Snapchat Bitmoji Notification
  • Easy Methods to Fix Snapchat Camera Not Working Black Screen Issue | Reasons & Troubleshooting Tips to Solve Snapchat Camera Problems
  • Detailed Procedure for How to Update Snapchat on iOS 14 for Free
  • What is Snapchat Spotlight Feature? How to Make a Spotlight on Snapchat?
  • Snapchat Hack Tutorial 2021: Can I hack a Snapchat Account without them knowing?

Copyright © 2023 · News Pro Theme on Genesis Framework · WordPress · Log in