Lists: Creating a list -Access values in List-Updating values in Lists-Nested lists -Basic list operations-List
Methods. Tuples: Creating, Accessing, Updating and Deleting Elements in a tuple – Nested tuples–
Difference between lists and tuples. Dictionaries: Creating, Accessing, Updating and Deleting Elements in
a Dictionary – Dictionary Functions and Methods - Difference between Lists and Dictionaries.
LISTS:
A list is a collection of different kinds of values or items. Since Python lists are mutable, we can change
their elements after forming.
CREATING A LIST
List is a versatile data type available in Python.
It is a sequence in which elements are written as a list of comma-separated values (items) between
square brackets.
The key feature of a list is that it can have elements that belong to different data type
Syntax,
List_variable = [vall, val2,...]
Example:
list_A = [1,2,3,4,5]
list_B = ['A', 'b', 'C', 'd', 'E']
list_C = ["Good", "Going"]
list_D = [1, 'a', "bed"]
ACCESS VALUES IN LISTS
Similar to strings, lists can also be sliced and concatenated. To access values in lists, square brackets are
used to slice along with the index or indices to get value stored at that index.
Syntax:
seq = List[start:stop:step]
Example:
X=list_A[0] # Access the first element (1)
X=list_A[-1] # Access the last element (5)
UPDATING VALUES IN LISTS
Once created, one or more elements of a list can be easily updated by giving the slice on the left-hand
side of the assignment operator.
You can also append new values in the list and remove existing value(s) from the list using the append ()
method and del statement respectively
Example:
num_list = [1,2,3,4,5,6,7,8,9,10]
print("List is",num_list)
num_list[5]=100
print("List after udpation is : ”, num_list")
num_list.append(200)
print("List after appending a value is ", num_list)
del num_list[3]
print("List after deleting a value is ", num_list)
Output:
List is [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
List after udpation is : ”, num_list
List after appending a value is [1, 2, 3, 4, 5, 100, 7, 8, 9, 10, 200]
List after deleting a value is [1, 2, 3, 5, 100, 7, 8, 9, 10, 200]
Note: append () and insert () methods are list methods. They cannot be called on other values such as
strings or integers.
NESTED LISTS:
Nested list means a list within another list. We have already said that a list has elements of different data
types which can include even a list
Example : listl = [1, 'a', "abc", [2,3,4,5], 8.9]
list1= [1, 'a', "abc", [2,3,4,5], 8.9]
i=0
while i<len(list1):
print(list1[i])
i+=1
Output:
1
a
abc
[2, 3, 4, 5]
8.9
Remember that you can specify an element in the nested list by using a set of indices. For example, to print
the second element of the nested list, we will write print(list[3] [1]).
BASIC LIST OPERATIONS:
OPERATION DESCRIPTION EXAMPLE OUTPUT
len Returns length of list len([l,2,3,4,5,6,7,8,9,10]) 10
concatenation Joins two lists [1,2,3,4,5] + [6,7,8,9,10] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
repetition Repeats elements in the ['nat','raj']*2 ['nat', 'raj', 'nat', 'raj']
List
in Checks if the value is 'a' in ['n','a','t'] True
present in the list
not in Checks if the value is not 3 not in [0,2,4,6,8] True
present in the list
max Returns maximum value num_list = [6,3,7,0,1,2,4,9] 9
in the list print(max(num_list))
min Returns minimum value num_list = [6,3,7,0,1,2,4,9] 0
in the list print(min(num_list))
sum Adds the values in the list num_list = [6,3,7,0,1,2,4,9] 32
that has numbers print(sum(num_list))
all Returns True if all num_list = [6,3,7,0,1,2,4,9] False
elements of the list are print(all(num_list))
true (or if the list is empty)
any Returns True if any element num_list = [6,3,7,0,1,2,4,9] True
of the list is true. If the list print(any(num_list))
is empty, returns False
list Converts an iterable listl = list("HELL0") ['H', 'E', 'L', 'L', '0']
(tuple, string, set, print(listl)
dictionary) to a list
sorted Returns a new sorted num_list = [6,3,7,0,1,2,4,9] [0, 1, 2, 3, 4, 6, 7, 9]
list. The original list is not print(sorted (num_list))
sorted.
LIST METHODS.
Method Description Syntax Example
Append( ) Adds an element to the end of the list. list.append(obj) n = [6,3,7,0,1,2,4,9]
n.append(10)
print(n)
output:
[6, 3, 7, 0, 1, 2, 4, 9, 10]
count ( ) Returns the number of occurrences of list.count(obj) n = [6,3,7,0,1,2,4,9]
a specified value in the list. print(n.count(4))
output:
1
index( ) Returns the index of the first list.index(obj) n = [6,3,7,0,1,2,4,9]
occurrence of a specified value in the print(n.index(7))
list output:
2
insert( ) Inserts an element at a specified index list.insert(index,obj) n = [6,3,7,0,1,2,4,9]
in the list. n.insert(3,100)
print(n)
output:
[6, 3, 7, 100, 0, 1, 2, 4, 9]
pop( ) Removes and returns the element at a List.pop([index]) n = [6,3,7,0,1,2,4,9]
specified index n.pop()
print(n)
output:
[6, 3, 7, 0, 1, 2, 4]
remove( ) Removes the first occurrence of a list.remove(obj) n = [6,3,7,0,1,2,4,9]
specified value from the list. n.remove(0)
print(n)
output:
[6, 3, 7, 1, 2, 4]
reverse( ) Reverses the order of elements in the list.reverse() n = [6,3,7,0,1,2,4,9]
list (modifies the original list). n.reverse()
print(n)
output:
[9, 4, 2, 1, 0, 7, 3, 6]
sort( ) Sorts the list in ascending order list.sort() n = [6,3,7,0,1,2,4,9]
(modifies the original list). n.sort()
print(n)
output:
[0, 1, 2, 3, 4, 6, 7, 9]
extend( ) Appends elements from another list.extend(list2) n1 = [0,1,2]
iterable (e.g., another list) to the end n2 = [3,4,5]
of the list. n1.extend(n2)
print(n1)
output:
[0, 1, 2, 3, 4, 5]
Note: Insert(), remove(), and sort() methods only modify the list and do not return any value. If you print the
return values of these methods, you will get None.
Example:
n1 = [0,1,2]
print(n1.insert(2, 250))
output:
None
TUPLES:
A tuple is an ordered, immutable, and iterable collection of elements. Tuples are similar to lists, but
unlike lists, once you create a tuple, you cannot change its contents (immutable).
CREATING TUPLE:
we can create a tuple by enclosing elements within parentheses () or by simply separating them with
commas without parentheses.
Example:
my_tuple = (1, 2, 3)
another_tuple = 4, 5, 6 # Creating a tuple without parentheses
Other Examples:
Tup1=( ) # empty tuple
Tup1=(5) # create with a single element
Tup1=(1,2,3,4,5) #create a tuple of integer
Tup1=(‘a’,’b’,’c’) #create a tuple of character
Tup1=(“abc”,”def”) #create a tuple of String
Tup1=(“abc”,”a”,1,1.5) #create a tuple of Mixed vaules
ACCESSING TUPLE:
we can access elements in a tuple using indexing,
first_element = Tup1[0]
Negative indexing works the same way as with lists.
first_element = Tup1[-4]
.UPDATING TUPLE:
Tuple is immutable and so, the value(s) in the tuple cannot be changed you can only extract the values
from the tuples
Example:
Tupl = (1,2,3,4,5)
Tup2 = (6,7,8,9,10)
Tup3 = Tupl+Tup2
print(Tup3)
Output:
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
DELETING ELEMENTS IN A TUPLE:
Since tuple is an immutable data structure, you cannot delete value(s) from it. Of course , you can create
a new tuple that has all elements in your tuple except the ones you don't want (those you wanted to be
deleted)
Example:
Tupl = (1,2,3,4,5)
del Tupl[3]
print(Tup1)
Output:
TypeError: 'tuple' object doesn't support item deletion
BASIC TUPLE OPERATIONS:
OPERATION EXAMPLE OUTPUT
len len((l,2,3,4,5,6,7,8,9,10)) 10
concatenation (1,2,3,4,5) + (6,7,8,9,10) (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Repetition ('nat','raj')*2 ('nat', 'raj', 'nat', 'raj')
membership 'a' in ('n','a','t') True
Iteration for i in (1,2,3,4,5,6,7,8,9,10): 1 2 3 4 5 6 7 8 9 10
print(i, end=' ')
max num_list = (6,3,7,0,1,2,4,9) 9
print(max(num_list))
min num_list = (6,3,7,0,1,2,4,9) 0
print(min(num_list))
Comparsion Tup1=(1,2,3) False
use<,>,== Tup2=(4,5,6)
print(Tup1>Tup2)
Convert to tuple print(tuple("Welcome")) ('W', 'e', 'l', 'c', 'o', 'm', 'e')
print(tuple([1,2,3,4,5])) (1, 2, 3, 4, 5)
NESTED TUPLES:
Python allows you to define a tuple inside another tuple. This is called a nested tuple. Nested tuples
allow you to create multi-dimensional data structures.
Example
nested_tuple = ((1, 2, 3), (4, 5, 6), (7, 8, 9))
DIFFERENCE BETWEEN LISTS AND TUPLES.
S.
List Tuple
No
1 Lists are mutable. Tuples are immutable.
2 Iteration in lists is time consuming. Iteration in tuples is faster
3 Lists are better for insertion and deletion operations Tuples are appropriate for accessing the elements
4 Lists consume more memory Tuples consume lesser memory
5 Lists have several built-in methods Tuples have comparatively lesser built-in methods.
Tuples operations are safe and chances of error are
6 Lists are more prone to unexpected errors
very less
Creating a list is slower because two memory
7 Creating a tuple is faster than creating a list.
blocks need to be accessed.
8 Lists are initialized using square brackets []. Tuples are initialized using parentheses ().
List objects cannot be used as keys for dictionaries Tuple objects can be used as keys for dictionaries
9
because keys should be hashable and immutable. because keys should be hashable and mutable.
10. List have order. Tuple have structure.