Python List and Tuple
Python List and Tuple
List is an ordered sequence of items. It is one of the most used data type in Python and is very
flexible. All the items in a list do not need to be of the same type. It is mutable.
Creating a list
Lists are enclosed in square brackets [ ] and each item is separated by a comma.
Example:
list1=[10,11,12,13,14,15]
list2=[101,102,"Hindi","English",10.50]
list3=['a','b','c','d','e']
Access Items from a List
List is a collection of items and each item has its own index value. Index of first item is 0 and
the last item is n-1. Here n is number of items in a list.
0 1 2 3 4 Index
10 20 30 40 50 Value
-5 -4 -3 -2 -1 Negative Index
List Items can be accessed using its index position.
Example:
list1=[10,11,12]
print("list1[0] :",list1[0] )
print("list1[1] :",list1[1])
print("list1[2] :",list1[2])
print("Negative Index")
print("list1[-1] :",list1[-1])
print("list1[-2] :",list1[-2])
print("list1[-3] :",list1[-3])
List Operations
The data type list allows manipulation of its contents through various operations as shown
below.
Concatenation
Python allows us to join two or more lists using concatenation operator depicted by the
symbol +.
Example 1:
list1 = [1,3,5,7,9]
list2 = [2,4,6,8,10]
list3=list1+list2
print(list3)
Example 2:
list1 = ['Red','Green','Blue']
list2 = ['Cyan', 'Magenta', 'Yellow','Black']
list3 = list1 + list2
print(list3)
Repetition
Python allows us to replicate a list using repetition operator depicted by symbol *.
Example:
list1 = ['Hello']
print(list1 * 4)
Membership
The membership operators ‘in’ checks if the element is present in the list and returns True,
else returns False.
Example:
list1 = ['Red','Green','Blue']
print('Green' in list1)
print('Cyan' not in list1)
Slicing of a List
List items can be accessed in subparts.
Example 1:
list1 = ['Red','Green','Blue','Cyan','Magenta']
print(list1[0:3]) #elements at index 0,1,2 are sliced
print(list1[2:4]) #elements at index 2,3 are sliced
print(list1[:]) #whole list
print(list1[:4]) #elements at index 0,1,2,3 are sliced
print(list1[0:]) #elements start from index 0 till last index
print(list1[::2]) #step size 2 on entire list
print(list1[0:6:2]) #slicing with a given step size 2
print(list1[-5:-1]) #elements at index -5,-4,-3,-2 are sliced
print(list1[::-1]) #negative step size,whole list in the reverse order
Example 2:
list1=["happy",[1,2,3,4,5],"orange",6,7,8,9,10]
print(list1[0][3]) # (It will print the value at the third index of 0 index value of list)
print(list1[1][3]) # (I will print the value at 4th index of 1st index value of list)
print(list1[0][0:2]) #(I will print the value at 0 and 1st index of 0 index value of list)
print(list1[2][3])
print(list1[3:8])
Traversing a List
We can access each element of the list or traverse a list using a for loop or a while loop.
List Traversal Using for Loop:
Example 1:
list1 = ['Red','Green','Blue','Yellow','Black']
for item in list1:
print(item)
Another way of accessing the elements of the list is using range() and len() functions:
Example 2:
list1 = [10,20,30,40,50]
for i in range(0,len(list1)):
print(list1[i])
List Traversal Using while Loop:
Example 1:
list1 = ['Red','Green','Blue','Yellow','Black']
i=0
while i < len(list1):
print(list1[i])
i+=1
Updating Lists
We can update single or multiple elements of lists by giving the slice on the left-hand side of
the assignment operator.
Example:
fruits=["apple","mango","oranges",'banana']
print(fruits)
fruits[0]="cherry" # update single value of index 0
print(fruits)
fruits[0:2]="cherry","Grapes" # update multiple values of index 0 and 1
print(fruits)
Add Item to a List
append() method is used to add an item to a List.
Example:
fruits=["apple","mango","oranges",'banana']
fruits.append("Grapes")
print(fruits)
extend() method is used to add multiple items at a time to a List.
Example:
fruits=["apple","mango","oranges",'banana']
fruits.extend(["Grapes","cherry"])
print(fruits)
To add an item at the specified index, use the insert() method:
Insert an item at the second position:
list1 = ["apple", "banana", "cherry"]
list1.insert(1, "orange")
print(list1)
Delete item from a List
Example 1:
fruits=["apple","mango","oranges",'banana']
del fruits[0] # deleted items from a list at index 0
print(fruits)
Example 2:
fruits=["apple","mango","oranges",'banana']
del fruits[0:2] # deleted first two items from a list
print(fruits)
Example 3:
fruits=["apple","mango","oranges",'banana']
del fruits # deleted entire list
print(fruits)
The clear() method empties the list
Example:
fruits= ["apple", "banana", "cherry"]
fruits.clear()
print(fruits)
Note: If you are using Python 2 or Python 3.2 and below, you cannot use the clear() method.
You can use the del operator instead.
list1 = ["apple", "banana", "cherry"]
del list1 [:]
print(list1)
To Remove an Item from the list using remove() method
list1 = ["apple", "banana", "cherry"]
list1.remove("banana")
print(list1)
list1=[11,2,31,4,15,4,6,71,8]
list1.sort(reverse=True)
print(list1)
list1=[11,2,33,4,55]
print(sorted(list1))
print(list1.sort())
list1=[11,2,31,4,15,4,6,71,8]
print(sorted(list1,reverse=True))
Note:
The sorted() function sorts the elements of a given iterable in a specific order (ascending or
descending) and returns it as a list.
The sort() method doesn't return any value and changes the original list.
Nested List
A List inside another list is called a nested tuple.
Program 1: create a nested list to store roll number, name and marks of students.
list1=[[101,"Aman",98],[102,"Geet",95],[103,"Sahil",87],[104,"Pawan",79]]
print("S_No"," Roll_No"," Name"," Marks")
for i in range(0,len(list1)):
print((i+1),'\t',list1[i][0],'\t',list1[i][1],'\t',list1[i][2])
Program 2 :Write a program to input n numbers from the user. Store these numbers in a
List. Print the maximum and minimum number from this List.
list1 = list() #create an empty List'
n = int(input("How many numbers you want to enter?: "))
for i in range(0,n):
num = int(input("Enter any number :\t"))
list1.append(num)
print('\nThe numbers in the list are:')
print(list1)
print("\nThe maximum number is:")
print(max(list1))
print("The minimum number is:")
print(min(list1))
Another way to do this is:
list1=[]
n=int(input("enter the no of elements"))
for i in range(0,n):
b=int(input("enter number"))
list1.append(b)
list1.sort()
print("largest element is",list1[n-1])
print("smallest element is",list1[0])
Program 3: Write a program to input n numbers from the user. Store these numbers in a
List. Print the mean of this List.
list1 = list() #create an empty list 'numbers'
total=0
n = int(input("How many numbers you want to enter?: "))
for i in range(0,n):
num = int(input("Enter any number :\t"))
list1.append(num)
print("List contains :",list1)
for j in list1:
total=j+total
mean=total/len(list1)
print('\nThe mean of list is:')
print(mean)
Another way to do this is using function:
list1=[2,3,4,5,6,1,2]
def Average(list1):
return(sum(list1)/len(list1))
average=Average(list1)
print("average of list is",average)
Program 4: Find the item in a list using Linear Search.
list1 = []
num = int(input("Enter size of list: \t"))
for n in range(num):
numbers = int(input("Enter any number: \t"))
list1.append(numbers)
found=False
x=int(input("Enter number to be search"))
for i in range(0,len(list1)):
if list1[i]==x:
found=True;
break
if found==False:
print("%d is not found"%x)
else:
print("%d found at %d position"%(x,i+1))
Program 5: Find the frequency of item in a list.
import collections
list1=[10,10,20,20,20,30,40,40,40,40,40,50]
ctr=collections.Counter(list1)
print(ctr)
The same can be done by using count()
list1=[10,10,20,20,20,30,40,40,40,40,40,50]
ctr=list1.count(20)
print(ctr)
Python Tuple
Tuple is an ordered sequence of elements of different data types same as list. The only
difference is that tuples are immutable. Tuples once created cannot be modified.
Elements of a tuple are enclosed in parenthesis (round brackets) and are separated by
commas. Like list and string, elements of a tuple can be accessed using index values, starting
from 0.
Example:
#tuple1 is the tuple of integers
tuple1 = (1,2,3,4,5)
print(tuple1)
#tuple2 is the tuple of mixed data types
tuple2 =('Economics',87,'Accountancy',89.6)
print(tuple2)
#tuple3 is the tuple with list as an element
tuple3 = (10,20,30,[40,50])
print(tuple3)
#tuple4 is the tuple with tuple as an element
tuple4 = (1,2,3,4,5,(10,20))
print(tuple4)
If there is only a single element in a tuple then the element should be followed by a comma.
If we assign the value without comma it is treated as integer. It should be noted that a
sequence without parenthesis is treated as tuple by default.
Example 1:
#Incorrect way of assigning single element to tuple
#tuple1 is assigned a single element
tuple1 = (20)
print(tuple1)
print(type(tuple1))
Example 2:
#Correct way of assigning single element to tuple
#tuple1 is assigned a single element
tuple1 = (20,)
print(tuple1)
print(type(tuple1))
A sequence without parentheses is treated as Tuple by default.
Example:
seq = 1,2,3
print(type(seq))
print(seq)
Accessing Elements in a Tuple
Elements of a tuple can be accessed in the same way as a list or string using indexing and
slicing.
tuple1 = (2,4,6,8,10,12)
print(tuple1[0])
print(tuple1[3])
print(tuple1[1+4])
Tuple is Immutable
Once a tuple is created, you cannot change its values. Tuples are unchangeable.
Example:
tuple1 = ("apple", "banana", "cherry")
tuple1 [1] = "blackcurrant"
print(tuple1) # The values will remain the same:
However an element of a tuple may be of mutable type.
e.g., a list.
#4th element of the tuple2 is a list
tuple2 = (1,2,3,[8,9])
#modify the list element of the tuple tuple2
tuple2[3][1] = 10
#modification is reflected in tuple2
print(tuple2)
Tuple Operations
Concatenation : Python allows us to join tuples using concatenation operator depicted by
symbol +. We can also create a new tuple which contains the result of this concatenation
operation.
Example 1:
tuple1 = (1,3,5,7,9)
tuple2 = (2,4,6,8,10)
tuple3=tuple1 + tuple2
print(tuple3)
tuple4 = ('Red','Green','Blue')
tuple5 = ('Cyan', 'Magenta', 'Yellow','Black')
tuple6 = tuple4 + tuple4
print(tuple6)
Example 2:
tuple1 = (1,2,3,4,5)
tuple1 = tuple1 + (6,)#single element is appended to tuple1
print(tuple1)
tuple1 = tuple1 + (7,8,9)#more than one elements are appended
print(tuple1)
Repetition: Repetition operation is depicted by the symbol *. It is used to repeat elements of a
tuple. We can repeat the tuple elements. The repetition operator requires the first operand to
be a tuple and the second operand to be an integer only.
Example:
tuple1 = ('Hello','World')
print(tuple1 * 3)
#tuple with single element
tuple2 = ("Hello",)
print(tuple2 * 4)
Membership: The in operator checks if the element is present in the tuple and returns True,
else it returns False.
Example:
tuple1 = ('Red','Green','Blue')
print('Green' in tuple1)
print('Green' not in tuple1)
Slicing : Like string and list, slicing can be applied to tuples also.
Example:
tuple1 = (10,20,30,40,50,60,70,80)
print(tuple1[2:7])
print(tuple1[0:len(tuple1)])#all elements of tuple are printed
print(tuple1[:5])
print(tuple1[2:])
print(tuple1[0:len(tuple1):2])#step size 2
print(tuple1[-6:-4])#negative indexing
print(tuple1[::-1])#tuple is traversed in reverse order
Loop Through a Tuple
tuple1 = ("apple", "banana", "cherry")
for x in tuple1:
print(x)
Remove Items
Note: You cannot remove items in a tuple.
Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple
completely:
Example
The del keyword can delete the tuple completely:
tuple1 = ("apple", "banana", "cherry")
del tuple1
print(tuple1) #this will raise an error because the tuple no longer exists
Built-in Functions and Methods for Tuples
len() : Returns the length or the number of elements of the tuple passed as the argument.
count() : Returns the number of times the given element appears in the tuple .
index() : Returns the index of the first occurrence of the element in the given tuple
sorted() : Takes elements in the tuple and returns a new sorted list. It should be noted that,
sorted() does not make any change to the original tuple
min() : Returns minimum or smallest element of the tuple
max() : Returns maximum or largest element of the tuple
sum() : Returns sum of the elements of the tuple
tuple() : Creates an empty tuple if no argument is passed Creates a tuple if a sequence is
passed as argument.
Example:
tuple1 = (10,20,30,40,50,70,60)
print("Length of Tuple :",len(tuple1))
print("Occurence of 10 in tuple :",tuple1.count(10))
print("Index of 10 in tuple :",tuple1.index(10))
print("Sorted Tuple :",sorted(tuple1))
print("Maximum Element :",max(tuple1))
print("Minimum Element :",min(tuple1))
print("Sum of all Elements :",sum(tuple1))
tuple2 = tuple()# Creates Empty Tuple
print(tuple2)
tuple3 = tuple('aeiou')#String converted into Tuple
print(tuple3)
tuple4 = tuple([1,2,3]) #List converted into Tuple
print(tuple4)
tuple5 = tuple(range(5))
print(tuple5)
Nested Tuples
A tuple inside another tuple is called a nested tuple.
Program 1: create a nested tuple to store roll number, name and marks of students.
st=((101,"Aman",98),(102,"Geet",95),(103,"Sahil",87),(104,"Pawan",79))
print("S_No"," Roll_No"," Name"," Marks")
for i in range(0,len(st)):
print((i+1),'\t',st[i][0],'\t',st[i][1],'\t',st[i][2])
Program 2 :Write a program to input n numbers from the user. Store these numbers in a
tuple. Print the maximum and minimum number from this tuple.
numbers = tuple() #create an empty tuple 'numbers'
n = int(input("How many numbers you want to enter?: "))
for i in range(0,n):
num = int(input("Enter any number :\t"))
numbers = numbers +(num,)
print('\nThe numbers in the tuple are:')
print(numbers)
print("\nThe maximum number is:")
print(max(numbers))
print("The minimum number is:")
print(min(numbers))
Program 3: Write a program to input n numbers from the user. Store these numbers in a
tuple. Print the mean of this tuple.
numbers = tuple() #create an empty tuple 'numbers'
total=0
n = int(input("How many numbers you want to enter?: "))
for i in range(0,n):
num = int(input("Enter any number :\t"))
numbers = numbers +(num,)
print("Tuple contains :",numbers)
for j in numbers:
total=j+total
mean=total/len(numbers)
print('\nThe mean of tuple is:')
print(mean)
Program 4: Write a program to search an item in a tuple using Linear search.
tuple1= tuple()
num = int(input("Enter size of tuple: \t"))
for n in range(num):
m = int(input("Enter any number: \t"))
tuple1=tuple1+(m,)
x = int(input("\nEnter number to search: \t"))
found = False
for i in range(len(tuple1)):
if tuple1[i] == x:
found = True
print("\n%d found at position %d" % (x, i+1))
break
if not found:
print("\n%d is not in tuple" % x)
Program 5: Find the frequency of item in a tuple.
import collections
tuple1=[10,10,20,20,20,30,40,40,40,40,40,50]
ctr=collections.Counter(tuple1)
print(ctr)
The same can be done by using count()
tuple1=[10,10,20,20,20,30,40,40,40,40,40,50]
ctr= tuple1.count(20)
print(ctr)