Unit 2 Python
Unit 2 Python
I. Lists
Creating Lists
Basic List Operation
Indexing and slicing in Lists
Built-in functions used on Lists
List Methods
II. Dictionaries
Creating Dictionary
Accessing and modifying key: value pair in Dictionaries
Built-in function used on Dictionary
Dictionary Methods
III. Tuples and Sets
Creating Tuples
Basic Tuple Operations
Indexing and Slicing in Tuples
Tuple Methods
Built-in function used on Tuples
Difference between List, Tuple, Set, and Dictionary
Using Zip () Function
Sets
Set Methods
Frozen set
1. Lists
List is Represent a group of individual objects as a single.
List objects are mutable i.e., list element(s) are changeable. It means that
we can modify the items stored within the list.
The sequence of various data types is stored in a list. A list is a collection
of different kinds of values or items.
List is maintained Insertion order.
It allowed Duplicates Objects.
It allowed Heterogeneous Objects.
List is Dynamic Because Based on our requirement we can increase the
size and decrease the size.
List elements will be placed within square brackets and with comma
separator.
Python supports both positive and negative indexes. +ve index means
from left to right where as negative index means right to left.
Creating Lists
list= []
print(list)
print(type(list))
output
[]
<class ‘list’>
2. If we know elements already then we can create list as follows
list=[10,20,30,40]
3. list with dynamic input
list=eval (input ("Enter List:"))
print(list)
print(type(list)
Output:
Enter List: [10,20,30,40]
[10, 20, 30, 40]
<class ‘list’>
print(l)
print(type(l))
output
[0,2,4,6,8]
<class ‘list>
Eg: s="durga"
l=list(s)
print(l)
output
[‘d’,’u’,’r’,’g’,’a’]
5. with split () function
l=s. split ()
print(l)
print(type(l))
output
<class ‘list’>
Note:
Sometimes we can take list inside another list, such type of lists is called nested
lists.
Example:
Let's see the various operations we can perform on the list in Python.
Concatenation: One list may be concatenated with itself or another list using
‘+’ operator.
Example:
List1 = [1, 2, 3, 4]
List2 = [5, 6, 7, 8]
concat_List = List1 + List2
print(concat_List)
output:
[1, 2, 3, 4, 5, 6, 7, 8]
Repeating the elements of the list: We can use the ‘*’ operator to repeat the
list elements as many times as we want.
Example:
my List = [1, 2, 3, 4]
Output:
[1, 2, 3, 4, 1, 2, 3, 4]
Example:
my List = [1, 2, 3, 4, 5, 6]
print (3 in my List)
Output:
True
False
True
Iterating through the list: We can iterate through each item within the list by
employing a for a loop.
Example:
my List = [1, 2, 3, 4, 5]
for n in my List:
print(n)
output:
Finding the length of List in python: len () method is used to get the length of
the list.
Example:
my List = [1, 2, 3, 4, 5]
output:
5
Accessing elements of List
We can access elements of the list either by using index or by using slice operator (:).
Elements stored in the lists are associated with a unique integer number known
as an index.
The first element is indexed as 0, and the second is 1, and so on. So, a list
containing six elements will have an index from 0 to 5.
For accessing the elements in the List, the index is mentioned within the index
operator ([ ]) preceded by the list's name.
Another way we can access elements/values from the list in python is using a
negative index. The negative index starts at -1 for the last element, -2 for the last
second element, and so on.
Example:
Output:
Syntax:
start ==>it indicates the index where slice has to start default value is 0.
stop ===>It indicates the index where slice has to end default value is max allowed
index of list i.e. length of the list.
Example:
my List = ['i', 'n', 't', 'v', 'i', 'e', 'w', 'b', 'i', 't']
output:
['i', 'n', 't', 'v', 'i', 'e', 'w', 'b', 'i', 't']
We can also use slicing to change, remove/delete multiple elements from the list.
List = [1, 2, 3, 4, 5, 6, 7, 8]
print (List)
# Changing elements from index 2nd to 5th
print (List)
print (List)
output:
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 1, 1, 1, 6, 7, 8]
[1, 2, 7, 8]
output
False
Returns True if all the items/elements present within the
all () list are true or if the list is empty.
Syntax:
all (list of iterables)
Example:
print (all ([False, True, True, False]))
output
False
Returns the sum of all the elements present within the list.
sum () Syntax: sum (iterable, start)
Example:
numbers = [1,2,3,4,5,1,4,5]
Sum = sum(numbers)
print (Sum)
Output:
25
Test each element of the list as true or not on the function
filter () passed as an argument thereto and returns a filtered
iterator.
Syntax: filter (function, sequence)
Example:
numbers= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def is_even(num):
return num % 2 == 0
even_numbers = list (filter (is_even, numbers))
print ("Even numbers:", even_numbers)
Returns a list after applying the function passed as an
map () argument to every element of the iterable.
Syntax: map (function, iterator)
Example:
list1 = [1, 2, 4, 3]
list2 = [1, 2, 5, 8]
list3 = [1, 2, 5, 8, 10]
list4 = [1, 2, 4, 3]
print cmp (list2, list1)
print cmp (list2, list3)
print cmp (list4, list1)
Creating Dictionary
1) d= {}
2) d=dict ()
d[100]="durga"
d[200]="ravi"
d[300]="shiva"
To access the items of a dictionary, refer to its key name. Key can be used inside
square brackets.
Example:
my_dict={'Name':'Ravi',"Age":'32','ID':'258RS569'}
output:
258RS569
32
If we tried to reference a key that is not present in our Python dictionary, we would get
the following error
Example:
output:
print(my_dict['Phone'])
The code demonstrates accessing a dictionary element using the get () method. It
retrieves and prints the value associated with the key 3 in the dictionary ‘Dict’.
Example:
Syntax: d[key]=value
Example:
#creating an empty dictionary
my_dict= {}
print(my_dict)
#adding elements to the dictionary one at a time
my_dict [1] ="James"
my_dict [2] ="Jim"
my_dict [3] ="Jake"
print(my_dict)
#modifying existing entry
my_dict [2] ="Apple"
print(my_dict)
#adding multiple values to a single key
my_dict [4] ="Banana, Cherry, Kiwi"
print(my_dict)
#adding nested key values
my_dict [5] = {'Nested’: {'1’: 'Scaler', '2’: 'Academy'}}
print(my_dict)
Output:
{}
{1: 'James', 2: 'Jim', 3: 'Jake'}
{1: 'James', 2: 'Apple', 3: 'Jake'}
{1: 'James', 2: 'Apple', 3: 'Jake', 4: 'Banana, Cherry, Kiwi'}
{1: 'James', 2: 'Apple', 3: 'Jake', 4: 'Banana, Cherry, Kiwi', 5: {'Nested': {'1': 'Scaler',
'2': 'Academy'}}}
The items of the dictionary can be deleted by using the del keyword as given below.
Example:
my_dict= {1: 'James', 2: 'Apple', 3: 'Jake', 4: 'Banana, Cherry, Kiwi'}
del my_dict [4]
print(my_dict)
Output:
{1: 'James', 2: 'Apple', 3: 'Jake'}
output:
True
It returns true if all the keys in the dictionary are true.
all () Syntax: all(dict)
Example:
dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}
all ({1:'',2:'','':''})
Output
False
It returns a new sorted list of keys in a dictionary.
sorted () Syntax: sorted(dict)
Example:
Output
[1,5,7,8]
Dictionary Methods
Output:
Tuple is exactly same as List except that it is immutable. i.e. once we create
Tuple object, we cannot perform any changes in that object.
The sequence of values stored in a tuple can be of any type, and they are
indexed by integers.
Each element in a tuple has a specific order that will never change because tuples
are ordered sequences.
Tuples are defined by enclosing elements in parentheses (), separated by a
comma.
Insertion Order is preserved.
Duplicates are allowed.
Heterogeneous objects are allowed.
We can preserve insertion order and we can differentiate duplicate objects by
using index. Hence index will play very important role in Tuple also.
Creating Tuples
1. t= () creation of empty tuple
2. t= (10,)
t=10,
creation of single valued tuple, parenthesis are optional, should ends with comma
3.t=10,20,30
t= (10,20,30) creation of multi values tuples & parenthesis are optional
4. By using tuple () function:
list= [10,20,30]
t=tuple(list)
print(t)
t=tuple (range (10,20,2))
print(t)
Deleting a Tuple
Example:
Tuple1 = (0, 1, 2, 3, 4)
del Tuple1
print (Tuple1)
Example 1:
Example 2:
Example 3:
tempTuple = ('apple')
print(type(tempTuple)) # OUTPUT: <class ‘str’>
tempTuple = ('apple',)
print(type(tempTuple)) # OUTPUT: <class ‘tuple’>
tempTuple = 'apple',
print(type(tempTuple)) # OUTPUT: <class ‘tuple’>
Indexing
Python allows you to access elements of a collection via negative indices. When
accessing using a negative index, -1 depicts the last element, and -n depicts the first
index where n is the length of the index.
Example:
Slicing in Tuples
start: is the starting index of the string, on which slicing operation has to be
performed. It determines from were slicing of the string will ‘begin’.
stop: is the stopping index of the slicing, ‘until’ which slicing operation has to
be performed i.e. stop index is excluded while generating the sub-tuple.
step: It is an optional argument that defines the steps when iterating the list i.e.
it allows us to skip over elements.
Example:
Tuple1 = tuple('GEEKSFORGEEKS')
Output:
Removal of First Element:
('E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S')
Tuple after sequence of Element is reversed:
('S', 'K', 'E', 'E', 'G', 'R', 'O', 'F', 'S', 'K', 'E', 'E', 'G')
Printing elements between Range 4-9:
('S', 'F', 'O', 'R', 'G')
Tuple Methods
1) index ()
index () method searches for a given element from the start of the list and returns
the position of the first occurrence.
Syntax:
Parameters:
element – The element whose lowest index will be returned.
start (Optional) – The position from where the search begins.
end (Optional) – The position from where the search ends.
Example:
t= (10,20,10,10,20)
print (t. index (10)) #0
2) count ()
count () method returns the count of the occurrences of a given element in a
list.
Syntax:
tuple_name. count(object)
Example:
T1 = (0, 1, 5, 6, 7, 2, 2, 4, 2, 3, 2, 3, 1, 3, 2)
res = T1. count (2)
print (res)
zip () method takes iterable containers and returns a single iterator object,
having mapped values from all the containers.
Python's zip () function is a built-in function that is used to combine two or
more iterables into a single iterable.
This function takes in any number of iterables (lists, tuples, sets, etc.) as
arguments and returns an iterator that aggregates elements from each of the
iterables into tuples.
Each tuple contains the i-th element from each of the input iterables.
Syntax: zip(*iterators)
Parameters: Python iterable or containers (list, string etc)
Return Value: Returns a single iterator object.
the zip () function is used to combine two or more lists (or any other iterables) into
a single iterable, where elements from corresponding positions are paired together.
Example:
name = [ "Manjeet", "Nikhil", "Shambhavi", "Astha”]
roll_no = [ 4, 1, 3, 2]
# using zip () to map values
mapped = zip (name, roll_no)
print(set(mapped))
Output:
{('Nikhil', 1), ('Shambhavi', 3), ('Manjeet', 4), ('Astha', 2)}
Output:
{'GEEKS': 2175, 'For': 1127, 'geeks': 2750}
Sets
Creation of Set
Example1:
s= {10,20,30,40}
print(s)
print(type(s))
Output
Syntax: set([iterable])
set () takes an iterable as an argument. In python, string, lists, and dictionaries are
iterable so you can pass them inside set ().
Example:
print(setWithMethod)
Set Methods
Syntax: set.add(element)
2. update () allows to add multiple elements. takes an iterable like string, list,
dictionary as an argument.
Example:
initialSet = {1, 2}
initialSet.add (3)
print(initialSet)
toAdd = [4, 5]
initialSet.update(toAdd)
print(initialSet)
Output:
{1, 2, 3}
{1, 2, 3, 4, 5}
1. remove(element) - This method removes the element from the set. If the
element is not present then it will throw an error.
2. discard(element) - This method removes the element from the set. If the
element is not present then the set will remain unchanged.
Example:
mySet = {1, 2, 3, 5}
mySet.remove(3)
mySet.discard(4)
mySet.clear()
print(mySet)
Output:
Before: {1, 2, 3, 5}
After: {1, 2, 5}
Using: {1, 2, 5}
set ()
4.pop ()
set pop () removes any random element from the set and returns the removed
element.
Syntax: set.pop ()
Example:
s1 = {9, 1, 0}
s1.pop ()
print(s1)
Ouput:
{9, 1}
5.copy ()
Example:
set1 = {1, 2, 3, 4}
# function to copy the set
set2 = set1.copy()
# prints the copied set
print(set2)
output:
{1, 2, 3, 4}
Frozen set
Frozen set is a built-in data type in Python. It is a set that is immutable (once
defined, cannot be changed).
It supports all non-modifying operations of the set. Operations like add () won’t
work in the case of a frozen set.
Frozen sets in Python are immutable objects that only support methods and
operators that produce a result without affecting the frozen set or sets to
which they are applied.
If no parameters are passed, it returns an empty frozen set.
Syntax: frozenset(iterable_object_name)
Example:
# Creating a Set
String = ('G', 'e', 'e', 'k', 's', 'F', 'o', 'r')
Fset1 = frozenset (String)
print (Fset1)
# No parameter is passed
print (frozenset ())
Output:
frozenset ({'F', 's', 'o', 'G', 'r', 'e', 'k'})
frozenset ()