Tuples and Lists

Python tuples and lists can be used to hold any number of data items of any data types.

A tuple is a collection of objects which are ordered and immutable. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.

__Tuples are immutable__, so once they are created we cannot change them. __Lists are mutable__, so we can easily insert items and remove items whenever we want.

1. Tuples

Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these comma-separated values between parentheses also. For example

In [1]:
tuple1 = ('physics', 'chemistry', 1997, 2000)
tuple2 = (1, 2, 3, 4, 5 )
tuple3 = "a", "b", "c", "d"

### The empty tuple is written as two parentheses containing nothing −
tuple4=( )

### NOTE: To write a tuple containing a single value you have to include a comma, even though there is only one value −
tuple5 = (50,)

print(tuple1)
print(tuple2)
print(tuple3)
print(tuple4)
print(tuple5)

del(tuple1, tuple2, tuple3, tuple4, tuple5) #### Deleting the tuples created earlier
('physics', 'chemistry', 1997, 2000)
(1, 2, 3, 4, 5)
('a', 'b', 'c', 'd')
()
(50,)

Accessing Values 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.

__Note :__ Indexing includes the lower bound and excludes the upper bound
In [2]:
tuple1 = ('physics', 'chemistry', 1997, 2000)
tuple2 = (1, 2, 3, 4, 5 )
tuple3 = "a", "b", "c", "d"

print(tuple1[0])
print(tuple1[1])
print(tuple1[2])

print(tuple1[1:2]) # (‘chemistry’,) Indexing includes the lower bound (index 1) and excludes the upper bound (index 2)
print(tuple2[1:3]) # (2,3)
print(tuple3[1:4]) # (‘b’,’c’,’d’)


del(tuple1, tuple2, tuple3) #### Deleting the tuples created earlier
physics
chemistry
1997
('chemistry',)
(2, 3)
('b', 'c', 'd')

Updating Tuples

Tuples are immutable which means you cannot update or change the values of tuple elements (append( ), pop( ), remove( ) will not work). But we are able to take portions of existing tuples to create new tuples:

tuple4=tuple2+tuple3[2:3]

In [3]:
tuple1 = ('physics', 'chemistry', 1997, 2000)
tuple2 = (1, 2, 3, 4, 5 )
tuple3 = "a", "b", "c", "d"
In [4]:
tuple1.append(2020)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-58f34019b9b9> in <module>
----> 1 tuple1.append(2020)

AttributeError: 'tuple' object has no attribute 'append'
In [5]:
tuple1.pop()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-5-0fe67a0487c5> in <module>
----> 1 tuple1.pop()

AttributeError: 'tuple' object has no attribute 'pop'
In [6]:
tuple1.remove(1997)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-6-c4fc7ad5a00f> in <module>
----> 1 tuple1.remove(1997)

AttributeError: 'tuple' object has no attribute 'remove'
In [7]:
tuple4=tuple2+tuple3[2:3]
print(tuple4)
(1, 2, 3, 4, 5, 'c')
In [8]:
del(tuple1, tuple2, tuple3, tuple4) #### Deleting the tuples created earlier

Examples for tuples

In [9]:
a=(1,2,3,4)
print(a[1:1])
()
In [10]:
# Different types of tuples
# Empty tuple
my_tuple = ()
print(my_tuple)

# Tuple having integers
my_tuple = (1, 2, 3)
print(my_tuple)

# tuple with mixed datatypes
my_tuple = (1, "Hello", 3.4)
print(my_tuple)

# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)

print(type(my_tuple[0]))
print(type(my_tuple[1]))
print(type(my_tuple[2]))
print(type(my_tuple))
()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))
<class 'str'>
<class 'list'>
<class 'tuple'>
<class 'tuple'>
In [11]:
my_tuple = 3, 4.6, "dog"
print(my_tuple)
print(type(my_tuple))

# tuple unpacking is also possible
a, b, c = my_tuple

print(a)      # 3
print(b)      # 4.6
print(c)      # dog
(3, 4.6, 'dog')
<class 'tuple'>
3
4.6
dog
In [12]:
# Accessing tuple elements using indexing
my_tuple = ('p','e','r','m','i','t')

print(my_tuple[0])   # 'p' 
print(my_tuple[5])   # 't'

# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))

# nested index
print(n_tuple[0][3])       # 's'
print(n_tuple[1][1])       # 4
p
t
s
4
In [13]:
# IndexError: list index out of range
print(my_tuple[6])
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-13-93b070875988> in <module>
      1 # IndexError: list index out of range
----> 2 print(my_tuple[6])

IndexError: tuple index out of range
In [14]:
# Index must be an integer
# TypeError: list indices must be integers, not float
my_tuple[2.0]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-14-82849314def3> in <module>
      1 # Index must be an integer
      2 # TypeError: list indices must be integers, not float
----> 3 my_tuple[2.0]

TypeError: tuple indices must be integers or slices, not float
In [15]:
# Negative indexing for accessing tuple elements
my_tuple = ('p', 'e', 'r', 'm', 'i', 't')

# Output: 't'
print(my_tuple[-1])

# Output: 'p'
print(my_tuple[-6])
t
p

2. Lists

Lists are similar to tuples as both can be used to hold any number of data items of any data types. The main difference in declaring the tuple and list is, parenthesis ( round brackets ) are used to declare tuples where as square brackets [ ] are used to declare/indicate lists.

Updating the lists

As lists are mutable, append( ), pop( ), remove( ) can be used to update the lists

In [16]:
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
print(type(list1))
print(type(list2))
<class 'list'>
<class 'list'>
In [17]:
list1.append(2020)
print(list1)
['physics', 'chemistry', 1997, 2000, 2020]
In [18]:
list1.remove(2000)
print(list1)
['physics', 'chemistry', 1997, 2020]
In [19]:
list1.pop()
print(list1)
['physics', 'chemistry', 1997]

3. Operations common for both tuple and list are as follows

Sl No Operation/Functions & Description
1 x in seq
True, when x is found in the sequence seq, otherwise False
2 x not in seq
False, when x is found in the sequence seq, otherwise True
3 x + y
Concatenate two sequences x and y
4 x n or n x
Replicate sequence x with itself n times
5 seq[ i ]
ith item of the sequence.
6 seq[ i:j ]
Slice sequence from index i to j
7 seq[ i:j:k ]
Slice sequence from index i to j with step k
8 len(seq)
Length or number of elements in the sequence
9 min(seq)
Minimum element in the sequence
10 max(seq)
Maximum element in the sequence
11 seq.count(x)
Count total number of elements in the sequence

Operations which are common for both Tuples and Lists

The following operations works for list as well: myList1 = [10, 20, 30, 40,40, 50,60,70,80,90,100] myList2 = [1,'psychology','journalism','computer science',94.2]

Operations on Tuples

In [20]:
myTuple1 = (10, 20, 30, 40,40, 50,60,70,80,90,100)
myTuple2 = (1,'psychology','journalism','computer science',94.2)

print("The items in myTuple1 are ", myTuple1)
print("The items in myTuple2 are ", myTuple2)
The items in myTuple1 are  (10, 20, 30, 40, 40, 50, 60, 70, 80, 90, 100)
The items in myTuple2 are  (1, 'psychology', 'journalism', 'computer science', 94.2)

x in sequence

In [21]:
print("x in seq demo")
if(30 in myTuple1):
    print('30 is present')
else:
    print('The number 30 not present')

if(31 in myTuple1):
    print('The number 31 present')
else:
    print('The number 31 not present')
x in seq demo
30 is present
The number 31 not present

x not in sequence

In [22]:
print("x not in seq demo")    
if ('psychology' not in myTuple2):
    print('psychology is not present')
else:
    print('psychology is present')
x not in seq demo
psychology is present

Concatination

In [23]:
newTuple=myTuple1 + myTuple2 # Concatination
print("newTuple contents are: ",newTuple) 
newTuple contents are:  (10, 20, 30, 40, 40, 50, 60, 70, 80, 90, 100, 1, 'psychology', 'journalism', 'computer science', 94.2)

x n or n x

In [24]:
myTuple1_3=myTuple1 * 3 #Add myTuple1 three times with itself
print("myTuple1 * 3 or 3 * myTuple1 is ",myTuple1_3) 
myTuple1 * 3 or 3 * myTuple1 is  (10, 20, 30, 40, 40, 50, 60, 70, 80, 90, 100, 10, 20, 30, 40, 40, 50, 60, 70, 80, 90, 100, 10, 20, 30, 40, 40, 50, 60, 70, 80, 90, 100)

sequence[ i ]

In [25]:
print("Third item in myTuple1 is ", myTuple1[2])
Third item in myTuple1 is  30

sequence[ i :j]

In [26]:
print("Slicing: The items in the index from 2 to 7 in myTuple1 are",myTuple1[2:7])
Slicing: The items in the index from 2 to 7 in myTuple1 are (30, 40, 40, 50, 60)

sequence[ i : j : k]

In [27]:
print("Slicing with steps k: The items in the index from 2 to 7 in k (2) steps in myTuple1 are",myTuple1[2:7:2])
Slicing with steps k: The items in the index from 2 to 7 in k (2) steps in myTuple1 are (30, 40, 60)

len( )

In [28]:
print("length of myTuple1 is ",len(myTuple1))
print("length of myTuple2 is ",len(myTuple2))
length of myTuple1 is  11
length of myTuple2 is  5

min( )

In [29]:
print("Minimum value in myTuple1 is ",min(myTuple1))
print("Maximum value in myTuple1 is ",max(myTuple1))
Minimum value in myTuple1 is  10
Maximum value in myTuple1 is  100

max( )

In [30]:
print("The no of times the item 40 appeared in myTuple1_3 is ",myTuple1_3.count(40)) #42 has two times in the tuple
The no of times the item 40 appeared in myTuple1_3 is  6

4. Operations only applicable to list are as follows

Sl No Operation/Functions & Description
1 seq.append(x)
Add x at the end of the sequence
2 seq.clear( )
Clear the contents of the sequence
3 seq.insert(i, x)
Insert x at the position i
4 seq.pop([i])
Return the item at position i, and also remove it from sequence. Default is last element
5 seq.remove(x)
Remove first occurrence of item x
6 seq.reverse( )
Reverse the list

Operation on List

In [31]:
myList1 = [10, 20, 30, 40, 50,60,70,80,90,100]
myList2 = [56, 42, 79, 42, 85, 96, 23]

print(myList1)
print(myList2)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
[56, 42, 79, 42, 85, 96, 23]

append( )

In [32]:
print("Append 60 to myList1")
myList1.append(60)
print(myList1)
Append 60 to myList1
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 60]

insert( )

In [33]:
myList2.insert(5, 17)
print("Content of myList2 after Inserting 17 in 5th index of myList2 are ", myList2)
Content of myList2 after Inserting 17 in 5th index of myList2 are  [56, 42, 79, 42, 85, 17, 96, 23]

pop( )

In [34]:
myList1.pop(3)
print("After pop(3) operation ie remove the item in index 3 in myList1 ", myList1)
After pop(3) operation ie remove the item in index 3 in myList1  [10, 20, 30, 50, 60, 70, 80, 90, 100, 60]

remove( )

In [35]:
print("Remove the first occurence of the item 42 from a sequence myList2")
myList2.remove(42)
print(myList2)
Remove the first occurence of the item 42 from a sequence myList2
[56, 79, 42, 85, 17, 96, 23]

reverse( )

In [36]:
myList1.reverse()
print("Reverse of myList1",myList1)
Reverse of myList1 [60, 100, 90, 80, 70, 60, 50, 30, 20, 10]

del

In [37]:
print()
del myList1[0]
print("myList1 content after deleting the item in 0th index is ",myList1)
myList1 content after deleting the item in 0th index is  [100, 90, 80, 70, 60, 50, 30, 20, 10]

clear( )

In [38]:
myList1.clear()
print("Contents of myList1 after clearing the items in the myList1",myList1)
Contents of myList1 after clearing the items in the myList1 []