PYTHON LIST
An iterable is any Python object capable of returning its members one at a time, permitting
it to be iterated over in a for-loop.
Examples of iterables include lists, tuples, and strings . Any sequence like list ,tuple, string ,
range can be iterated over in a for-loop. Non-sequential collections, like dictionaries and
sets; these are iterables as well.
List in python is a mutable , linear data structure of variable length, allowing mixed-type .
Mutable means that the contents of the list may be altered. Lists in python use zero based
indexing .
Thus all lists have index values 0….n-1, where n is the number of elements in the list. Lists
are denoted by a comma separated list of elements with in square brackets
Accessing List Data
Example:
>>>my_list= [ ‘Apple’ , 10,12.00 , True , 10 ]
>>>print ( my_list[ 0 ] )
>>>Apple
>>>my_list= [ ‘Apple’ , 10,12.00 , True , 10 ]
>>>print ( my_list[ 0 : 3 ] )
>>>[ ‘Apple’ , 10, 12.00 ]
>>>my_list= [ ‘Apple’ , 10,12.00 , True , 10 ]
>>>print (my_list [ -3 : -1 ] )
>>>[ 12.00, True]
Creation of lists:
list() function creates a list for the given iterable object
Example:
#creating empty list
>>>l=[]
>>>print(type(l))
>>><class ‘list’>
>>> l=list()
>>>print(type(l))
>>> <class ‘list’>
#creating list for the given sequence
>>>l = list( range(1,11) )
list object
0 1 2 3 4 5 6 7 8 9
l
1 2 3 4 5 6 7 8 9 10
1896172366784 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
1896172366784
>>>print(l)
>>> [1,2,3,4,5,6,7,8,9,10]
>>>l=list(‘python’)
>>>print(l)
>>> [‘ p ’ , ’ y ’ , ’ t ’ , ’ h ’ , ’ o ’ , ’ n ‘ ]
List unpacking:
my_list= [‘Apple’,10,12.50]
x,y,z=my_list
print(x,y,z)
print(type(x),type(y),type(z))
Nested Lists
List can contain elements of any type, including other sequences.
Thus lists can be nested to create arbitrarily complex data structures
a=[ [1,2,3],[4,5,6] ,[7,8,9] ]
print( a[1] ) #[4,5,6]
print(a[1][1]) # 5
print(a[2][0]) #7
List Functions
Name Description
list() Creates a list out of an iterable
len() Returns the number of elements in the list
sum() Adds all items of an iterable
min() Gets the smallest item in a sequence
max() Gets the largest item in a sequence
Sort() Returns a new list of sorted items in iterable
reverse() Reverses an iterator
enumerate () returns an enumerate object
append() Append object to the end of the list.
insert() Insert object before index.
extend() Extend list by appending elements from the
iterable.
pop() Remove and return item at index (default last).
Raises IndexError if list is empty or index is out of
range.
remove() Remove first occurrence of value.
Raises ValueError if the value is not present.
clear() Remove all items from list.
Operations on lists
s=[1,2,3,4] w=[5,6]
len(s) #4
s[0] #1
s[1:4] #[2,3,4]
s[1:] #’[2,3,4]
s.count(‘x’) #0
s.count(4) #1
s.index(‘e’) #ValueError
s.index(3) # 2
2 in s #True
s+w # [1,2,3,4,5,6]
min(s) #1
max(s) #4
sum(s) #10
List functions
#item reassignment
>>> fruit = [ ‘ banana’ , ‘ apple ‘ , ‘ cherry’ ]
>>> fruit [ 2 ] = ‘orange’
>>>print(fruit)
>>> [ ‘ banana’ , ‘ apple ‘ , ‘ orange ’ ]
#delete an item from a list
>>> fruit = [ ‘ banana’ , ‘ apple ‘ , ‘ cherry’ ]
>>> del fruit [1]
>>>print(fruit)
>>> [ ‘ banana’ , ‘ cherry’ ]
#list methods that modify the list
# append() : append object to the end of the list.
>>> fruit = [ ‘ banana’ , ‘ apple ‘ , ‘ cherry’ ]
>>> fruit.append(‘peach’)
>>>print(fruit)
>>> [ ‘ banana’ , ‘ apple ‘ , ‘ cherry’,’ peach’ ]
#insert() : Insert object before index.
>>> fruit = [ ‘ banana’ , ‘ apple ‘ , ‘ cherry’ ]
>>> fruit.insert(2,’grapes’)
>>>print(fruit)
>>> [ ‘ banana’ , ‘ apple ‘ , ‘grapes’, ‘ cherry’ ]
#sort(): Sort the list in ascending order and return None.
>>> fruit = [ ‘ banana’ , ‘ apple ‘ , ‘ cherry’ ]
>>> fruit.sort()
>>>print(fruit)
>>> [ ‘apple ‘ , ‘banana’ , ‘cherry’]
#reverse() : reverse the elements in the list
>>> fruit.reverse()
>>>print(fruit)
>>> [‘cherry’ , ’apple’, ‘banana’]
#pop() : Remove and return item at index (default last).
>>>fruit=["apple","orange","grapes","banana","orange"]
>>>print(fruit.pop())
>>>orange
>>>print(fruit)
>>>["apple","orange","grapes","banana"]
#pop(index) : pop an item at given index
>>>fruit=["apple","orange","grapes","banana"]
>>>print(fruit.pop(0))
>>>apple
>>>print(fruit)
>>>["orange","grapes","banana"]
>>>fruit=[‘apple’,’orange’,’grapes’,’banana’]
>>>print(fruit.pop(10))
>>> indexError: pop index out of range
Example:
#len(): returns number of elements in the list
>>>courses=['History','Math','Physics','CompSci']
>>>print(len(courses))
>>>4
#s[k]: index operation => returns the element at kth index
>>>courses=['History','Math','Physics','CompSci']
>>>print(courses[3])
>>>CompSci
>>>print(courses[-1])
>>>CompSci
#print(courses[4]) #indexError: list index out of range
#s[start:stop:step] slice operation => returns subsequence
>>>courses=['History','Math','Physics','CompSci']
>>>print(courses[0:2])
>>>[‘History’,’Math’]
>>>print(courses[2:])
>>>[‘Physics’,’CompSci’]
>>>print(courses[:2])
>>>[‘History’,’Math’]
#append() : append object to the end of the list.
>>>courses=['History','Math','Physics','CompSci']
>>>courses.append('Art')
>>>print(courses)
>>>['History','Math','Physics','CompSci' , ‘Art’]
#insert() : Insert object before index.
>>> courses=['History','Math','Physics','CompSci']
>>>courses.insert(0,'Art')
>>>print(courses) )
>>>[‘Art’, 'History','Math','Physics','CompSci' ]
#extend() : Extend list by appending elements from the iterable.
>>>courses=['History','Math','Physics','CompSci']
>>>courses_2=['Art','Education']
>>>courses.extend(courses_2)
>>>print(courses)
>>>['History','Math','Physics','CompSci', 'Art','Education']
#remove(): Remove first occurrence of value.
>>> courses=['History','Math','Physics','CompSci']
>>>courses.remove('Math')
>>>print(courses)
>>>[ 'History', 'Physics' , 'CompSci' ]
#pop(): Remove and return item at index (default last).
>>> courses=['History','Math','Physics','CompSci']
>>>popitem=courses.pop()
>>>print(popitem)
>>>CompSci
>>>print(courses)
>>>=['History','Math','Physics']
#sort(): Returns a sorted items in iterable
>>> courses=['History','Math','Physics','CompSci']
>>>courses.sort()
>>>print(courses)
>>> [CompSci'.'History','Math','Physics',']
#reverse(): reverses the items in the list
>>> courses=['History','Math','Physics','CompSci']
>>>courses.reverse()
>>>print(courses)
>>> [‘CompSci’,’Physics’,’Math’,’History’]
List comprehension
list = [ expression for item in iterable if condition]
Example:
#create a list of numbers in the given range
>>>nums=[ x for x in list( range ( 1 , 11 ) ) ]
>>>print(nums)
>>>[1,2,3,4,5,6,7,8,9,10]
#create a list of even numbers in the given range
>>>even_nums= [ x for x in range(1,11) if x%2==0]
>>>print(even_nums)
>>> [2,4,6,8]
PYTHON TUPLE
A tuple is an immutable linear data structure .
Thus, in contrast to lists, once a tuple is defined it can not be altered. Otherwise , tuples and
lists are essentially the same.
To distinguish tuples and from lists , tuples are denoted by parentheses instead of square
brackets
Example:
Creating a tuple object
>>>t=() #empty tuple object
>>>print(type(t))
>>><class 'tuple'>
#defining a tuple with one element
>>>t=( 10 , )
>>>print(type(t))
>>> <class 'tuple'>
>>>t=(10,20,30,40,50) #tuple with elements
>>>print(t)
>>> (10, 20, 30)
#creating a tuple using tuple function
>>>t=tuple() #emplty tuple
>>>t=tuple(range(1,11)) #creates a tuple object of the given sequence (Iterable)
Indexing and slicing operations:
>>>t=(10,20,30,40,50)
>>>print(t[0]) #10
>>>print(t[-3]) #30
>>>print(t[1:3]) # (10,20)
>>>t[0]=777
>>>TypeError: 'tuple' object does not support item assignment
Operators
#concatenation operator
>>>t1=(10,20,30)
>>>t2=(40,50,60)
>>>t3=t1 + t2
>>>print(t3)
>>> (10,20,30,40,50,60)
#repetition operator (concatenating the same tuple )
>>>t1=(10,20,30)
>>>print(t1*3)
>>> (10,20,30,10,20,30,10,20,30)
tuple packing and unpacking
#tuple packing
>>>a=10
>>>b=20
>>>c=30
>>>t=(a ,b ,c)
>>>print(t)
>>>(10,20,30)
Approach II
>>> a , b , c = 10 , 20 ,30
>>> t = a , b , c
>>>print(t)
>>>(10,20,30)
#tuple unpacking
>>>weather = ( 'Mon' , '08/11/2021' , 35 , 'Sunny' )
>>>x ,y ,z, w = weather
>>> print( x , w )
>>> Mon Sunny
unpacking tuple to list
>>> num = (1,2,3,4)
>>>a ,b ,c ,d = num
>>>print( a ,b ,c ,d )
>>>1 2 3 4
>>> num = (1,2,3,4)
>>> a ,*b , c = num
>>>print(a)
>>>1
>>>print(type(b))
>>><class 'list'>
>>>print(b)
>>>[2,3]
>>>print(c)
>>>4
Nesting of tuples in list
#append an element to the list
>>>l = [ (1 , 2 , 3 ) , ( 4 , 5 , 6) ]
>>>print(l)
>>> [ ( 1 , 2 , 3) , ( 4 , 5 , 6 ) ]
>>> l.append( ( 7 , 8 , 9 ) )
>>>print( l )
>>> [ ( 1, 2, 3 ), ( 4, 5, 6 ), ( 7, 8, 9 ) ]
#remove an element from the list
>>>l=[(1,2,3),(4,5,6)]
>>>print(l)
>>> [ ( 1 , 2 , 3) , ( 4 , 5 , 6 ) ]
>>> l.remove( (1,2,3) )
>>>print(l)
>>> [ ( 4 , 5, 6 ) , ( 7 , 8 , 9 ) ]
#accessing the elements in the list
>>>l=[ ( 1 , 2 , 3 ) , (4 , 5 , 6 ) ]
>>>print(l)
>>> [ ( 1 , 2 , 3) , ( 4 , 5 , 6 ) ]
>>>print( l [1] [0] )
>>> 4
>>>l=[ ( 1 , 2 , 3 ) , (4 , 5 , 6 ) ]
>>> l [ 1 ] [ 0 ] = 111
>>> TypeError: 'tuple' object does not support item assignment
Nesting of lists in tuples
>>>t=( [ 'a' ,'b', 'c' ] , [ 'd' ,'e', 'f' ] )
>>>print(t)
output
>>> (['a', 'b', 'c'], ['d', 'e', 'f'])
>>>t=( [ 'a' ,'b', 'c' ] , [ 'd' ,'e', 'f' ] )
>>>print(t)
>>> t[0].append('z')
>>>print(t)
Output
>>> ( ['a', 'b', 'c', 'z'] , ['d', 'e', 'f'] )
List vs Tuple
List Tuple
1) List is a group of Comma separated 1) Tuple is a Group of Comma separated
Values within Square brackets . Values within Parenthesis . Parenthesis are
optional.
Example
l = [10, 20, 30, 40] Example
t = (10, 20, 30, 40)
t = 10, 20, 30, 40
2) List Objects are Mutable i.e. once we 2) Tuple Objects are Immutable i.e. once we
creates List Object we can make any creates Tuple Object we cannot change its
changes in that Object. content.
Example:
l=[10,20,30,40] t=(10,20,30,40)
l[1] = 70 t[1] = 70
print(l) ValueError: tuple object does
[10,70,30,40] not support item assignment.
3) List Objects can not used as Keys for 3) Tuple Objects can be used as Keys for
Dictionaries because Keys should be Dictionaries because Keys should be Hashable
Hashable and Immutable. and Immutable.
PYTHON SETS
A set is an unordered collection of distinct items. Every set element is unique (no duplicates)
and must be immutable (cannot be changed). However, a set itself is mutable. We can add
or remove items from it. Sets can also be used to perform mathematical set operations like
union, intersection, symmetric difference, etc.
Creating a set object
#creating empty set object
>>>s=set()
>>>print(type(s))
>>> <class ‘set’>
>>> s = {}
>>> type(s)
>>> <class 'dict'>
#creating a set with elements
>>>s={10,20,30,40,50}
20
10
s
2208288661280 40
30
50
2208288661280
>>>print(s)
>>> {50, 20, 40, 10, 30} #no ordering is maintained
Modifying a set in Python
Set is unordered so we can not access or modify an element by indexing . slicing is also not
a valid operation on sets.
However , a single element can be added to a set using the add() method, and multiple
elements can be added using the update() method. The update() method can take tuples,
lists, strings or other sets as its argument. Duplicates are avoided while adding the elements
to the set .
#add() : adds a single element to the set
>>> s={1,2,3}
>>> s.add(4)
>>>print(s)
>>> {1,2,3,4}
#update(): add multiple elements to the set
>>> s={1,2,3}
>>> s.update([2,3,4,5])
>>>print(s)
>>> {1, 2, 3, 4, 5}
>>> s={1,2,3}
>>>s.update( [4 , 5 ] , ( 1 , 6 , 8 ) , { 6 , 7} )
>>>print(s)
>>>{1, 2, 3, 4, 5, 6,7, 8}
Removing elements from a set
A particular item can be removed from a set using the methods discard() and remove().
The only difference between the two is that the discard() function leaves a set unchanged if
the element is not present in the set. On the other hand, the remove() function will raise an
error in such a condition (if element is not present in the set).
pop() method removes and returns an arbitrary item .Since set is an unordered data type,
there is no way of determining which item will be popped. It is completely arbitrary.
clear() method removes all the items from the set
#creating a set object
S={1,2,3}
#discard() : remove a particular item from the set
>>> s.discard(4) #no output
#remove(): remove a particular item from the set .
>>> s.remove(4)
>>> KeyError: 4
#pop() : removes and return an arbitrary item from the set
>>>s.pop()
>>>1
#clear() : removes all items from the set
>>> s={1,2,3}
>>> s.clear()
>>>print(s)
>>>set() #empty set
Python Set Operations
Sets can be used to carry out mathematical set operations like union, intersection,
difference and symmetric difference.
Union of A and B is a set of all elements from both sets.
Union is performed using | operator. Same can be accomplished using the union() method.
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
>>> #union of two sets using | operator
>>> print( A | B )
>>>{1, 2, 3, 4, 5, 6, 7, 8}
>>>#using union method
>>> A.union(B)
>>>{1, 2, 3, 4, 5, 6, 7, 8}
Intersection of A and B is a set of elements that are common in both the sets.
Intersection is performed using & operator. Same can be accomplished using the
intersection() method.
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
>>> #intersection of two sets using & operator
>>> print(A & B)
>>>{4,5}
>>>#using intersection method
>>> A.intersectioin(B)
>>>{1, 2, 3, 4, 5, 6, 7, 8}
Difference of the set B from set A (A - B) is a set of elements that are only in A but not in B.
Similarly, B - A is a set of elements in B but not in A.
Difference is performed using - operator. Same can be accomplished using the difference()
method.
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
>>>#set difference using – operator
>>>print(A – B )
>>> {1,2,3}
#set difference using difference method
>>>A.difference(B)
>>>{1,2,3}
Symmetric Difference of A and B is a set of elements in A and B but not in both (excluding
the intersection).
Symmetric difference is performed using ^ operator. Same can be accomplished using the
method symmetric_difference().
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
>>>#symmetic difference using ^ operator
>>> print(A^B)
>>> {1,2,3,6,7,8}
>>> A.symmetic_difference(B)
>>> {1,2,3,6,7,8}
PYTHON DICTIONARY
Python dictionary is an unordered collection of items. Each item of a dictionary has a key ,
value pair.
Creating python dictionary
Create a dictionary by enclosing items with in the curly braces { } separated by commas
An item in the dictionary has a key and a corresponding value that is expressed as a pair
(key: value).
Keys must be immutable and unique . values can be of any data type and can repeat
>>>#creating empty dictionary
>>> my_dict={}
>>>print(type(my_dict)
>>><class ‘dict’>
# dict() : convert compatible constructs into dictionary
>>>my_dict=dict() #creates empty dictionary
>>>print(my_dict)
>>>{}
>>> my_dict= { ( [ 1 , 2 ] , [ 2 , 4 ] , [ 3 , 6 ] ) }
>>>print(my_dict)
>>>{1: 2, 2: 4, 3: 6}
Defining an empty dictionary and adding items
#create an empty dictionary
>>>emp_dict={}
#adding key-value pairs to the dictionary
>>>emp_dict[111]=’Alan’
>>>emp_dict[222]=’Keith’
>>>emp_dict[333]=’Joe’
>>>print(emp_dict)
>>>{111:’Alan’,222:’Keith’,333:’Joe’}
Accessing items from Dictionary
indexing is used with other container types to access values, dictionary uses keys.
Key can be used either inside square brackets or with the get() method
Python dictionary is unordered. So to get a value from it, put its key in square brackets.
>>>student_dict = { ‘name’ : ’Jack’ , ’gpa’ : 2.5}
>>>student_dict[‘name’]
>>> ‘Jack’
>>>student_dict[‘gpa’]
>>> 2.5
# Using the key in square brackets gives us a KeyError when the key does not exist
>>>student_dict[‘course’]
>>> KeyError: 'course'
#get() method to access the values
>>>student_dict = { ‘name’ : ’Jack’ , ’gpa’ : 2.5}
>>>student_dict.get(‘name’)
>>>’Jack’
>>> student_dict.get(‘course’)
>>>
>>>print(student_dict.get(‘course’) )
>>>None
Note: when the key doesn’t exist, the get() function returns the value None. that indicates
an absence of value
Updating the Value of an Existing Key
If the key exists then value of a key can be updated by reassigning the value using square
brackets. If the key does not exist then a new key-value pair is added to the dictionary
>>>student_dict={‘name’:’Jack’, ‘gpa’:2.5}
>>>student_dict[‘gpa’]=3.5
>>>print(student_dict)
>>> { ‘name’ : ‘Jack’ , ’gpa’ : 3.5 }
Deleting items from dictionary
delete a particular item in a dictionary by using the pop() method. This method deletes an
item with the provided key and returns the value.
The popitem() method can be used to delete and return an arbitrary (key, value) item pair
from the dictionary. All the items can be deleted at once, using the clear() method.
The del keyword is to delete individual items or the entire dictionary itself.
#pop(): delete a particular item in the dictionary
>>> emp_dict={111:'Alan',222:'Keith',333:'Joe'}
>>> emp_dict.pop(222)
'Keith'
>>> print(emp_dict)
{111: 'Alan', 333: 'Joe'}
#popitem() : deletes and returns an arbitrary item
>>> emp_dict={111:'Alan',222:'Keith',333:'Joe'}
>>> emp_dict.popitem()
>>> (333, 'Joe')
#clear(): all the items can be deleted at once
>>> emp_dict={ 111:’Alan’,222:’Keith’,333:’Joe’}
>>>emp_dict.clear()
>>>print(emp_dict)
>>>{}
#del : Deleting a single key-value pair
>>> emp_dict={ 111:’Alan’,222:’Keith’,333:’Joe’}
>>>del emp_dict[333]
>>>print(emp_dict)
>>>{111:’Alan’,222:’Keith’}
#del : to delete entire dictionary
>>> emp_dict={ 111:’Alan’,222:’Keith’,333:’Joe’}
>>> del emp_dict
>>> print(emp_dict)
>>>NameError: name 'emp_dict' is not defined
Dictionary Unpacking
Iterating over a dictionary . for each item in the dictionary unpack the key to k and value to
v
daily_temps ={ ‘Sun’ : 68.8 ,‘Mon’ : 70.2 , ‘Tue’ : 67.2, ‘Wed’ : 71.8, ‘Thur’ : 73.2, ’ Fri ’ : 75.6 ,
‘ Sat ’ : 74.3 }
print(‘Week Day’ ,’\t’ ,’Temperature’)
for k,v in daily_temps.items():
print(k,’\t’,v)
output:
Weekday temperature
Sun 68.8
Mon 70.2
Tue 67.2
Wed 71.8
Thur 73.2
Fri 75.6
Sat 74.3
Dictionary in-built methods
keys() :The keys() method returns all the keys in a Python dictionary.
>>> emp_dict={111:’Alan’,222:’Keith’,333:’Joe’}
>>>emp_dict.keys()
>>> dict_keys([111, 222, 333])
values() : The values() method returns a list of values in the dictionary.
>>> emp_dict={111:’Alan’,222:’Keith’,333:’Joe’}
>>>emp_dict.values()
>>>dict_values(['Alan', 'Keith', 'Joe'])
items() : This method returns key-value pairs in the dictionary
>>>emp_dict={111:’Alan’,222:’Keith’,333:’Joe’}
>>>emp_dict.items()
>>> dict_items( [ ( 111, 'Alan' ) , ( 222, 'Keith' ) , ( 333 , 'Joe' ) ] )
Dictionary Comprehension
Dictionary comprehension is an elegant and concise way to create a new dictionary from an
iterable in Python.
Dictionary comprehension consists of an expression pair (key: value) followed by a for
statement inside curly braces {}.
squares = { x : x * x for x in range ( 1 , 6 ) }
print(squares)
doubles = { x : 2 * x for x in range ( 1 , 6 ) }
print(doubles)
Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10}