Python Unit2
Python Unit2
PYTHON COLLECTIONS
The collection Module in Python provides different types of containers. A Container is an object that
is used to store different objects and provide a way to access the contained objects and iterate over
them. Some of the built-in containers are Tuple, List, Dictionary, etc. There are four collection data
types in the Python programming language:
b) Access tuples - We can use the index operator [] to access an item in a tuple, where the index
starts from 0. So, a tuple having 6 elements will have indices from 0 to 5. Trying to access an
index outside of the tuple index range(6,7,... in this example) will raise an IndexError.
Ex: # Accessing tuple elements using indexing
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't
Negative Indexing- Python allows negative indexing for its sequences. The index of -1 refers
to the last item, -2 to the second last item and so on.
Ex: # 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])
c) Update tuples - Tuples are immutable, which means you cannot update or change the values
of tuple elements. You are able to take portions of the existing tuples to create new tuples as
the following example demonstrates –
Ex: # Python program to demonstrate concatenation of tuples.
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('Geeks', 'For', 'Geeks')
Tuple3 = Tuple1 + Tuple2
2. List - list is a type of container in Data Structures, which is used to store multiple data at the
same time. The list in Python are ordered and have a definite count. The elements in a list are
indexed according to a definite sequence and the indexing of a list is done with 0 being the
first index. Each element in the list has its definite place in the list, which allows duplicating of
elements in the list, with each element having its own distinct place and credibility. The
following operations can be performed on a list:
a) Create - In Python programming, a list is created by placing all the items (elements) inside
square brackets [], separated by commas. It can have any number of items and they may be
of different types (integer, float, string etc.).
Ex: # empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
We can use the index operator [] to access an item in a list. In Python, indices start at 0. So, a
list having 5 elements will have an index from 0 to 4.
Trying to access indexes other than these will raise an IndexError. The index must be an
integer.
# List indexing
my_list = ['p', 'r', 'o', 'b', 'e']
# Output: p
print(my_list[0])
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to
the second last item and so on.
# Negative indexing in lists
my_list = ['p','r','o','b','e']
print(my_list[-1])
print(my_list[-5])
b) Slicing - We can access a range of items in a list by using the slicing operator :(colon).
Ex: # List slicing in Python
my_list = ['p','r','o','g','r','a','m','i','z']
We can add one item to a list using the append() method or add several items using extend()
method.
Ex: # Appending and Extending lists in Python
odd = [1, 3, 5]
odd.append(7)
print(odd)
odd.extend([9, 11, 13])
print(odd)
d) Delete - We can delete one or more items from a list using the keyword del. It can even delete
the list entirely.
Ex: # Deleting list items
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
# delete one item
del my_list[2]
# delete multiple items
del my_list[1:5]
# delete entire list
del my_list
We can use remove() method to remove the given item or pop() method to remove an item
at the given index. The pop() method removes and returns the last item if the index is not
provided. We can also use the clear() method to empty a list.
Ex: my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
# Output: 'm'
print(my_list.pop())
my_list.clear()
b) Accessing - While indexing is used with other data types to access values, a dictionary uses
keys. Keys can be used either inside square brackets [] or with the get() method. If we use the
square brackets [], KeyError is raised in case a key is not found in the dictionary. On the other
hand, the get() method returns None if the key is not found.
# get vs [] for retrieving elements
my_dict = {'name': 'Jack', 'age': 26}
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
# KeyError
print(my_dict['address'])
c) Changing and Adding - Dictionaries are mutable. We can add new items or change the value
of existing items using an assignment operator. If the key is already present, then the existing
value gets updated. In case the key is not present, a new (key: value) pair is added to the
dictionary.
Ex:# Changing and adding Dictionary Elements
my_dict = {'name': 'Jack', 'age': 26}
# update value
my_dict['age'] = 27
# add item
my_dict['address'] = 'Downtown'
# add item
my_dict['address'] = 'Downtown'
d) Delete - The pop() method removes the item with the specified key name.
Ex: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
The del keyword removes the item with the specified key name:
Ex: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
The del keyword can also delete the dictionary completely
Ex: del thisdict
4. Set - Sets are used to store multiple items in a single variable. A set is a collection which is
both unordered and unindexed. Sets are written with curly brackets. Set items are
unordered, unchangeable, and do not allow duplicate values. Unordered means that the
items in a set do not have a defined order. Set items can appear in a different order every
time you use them, and cannot be refferred to by index or key. The following operations can
be performed on sets:
a. Create -
Ex: my_set = {1, 2, 3}
print(my_set)
b. Access - You cannot access items in a set by referring to an index or a key. But you can loop
through the set items using a for loop, or ask if a specified value is present in a set, by using
the in keyword.
Ex: thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
c. Add - Once a set is created, you cannot change its items, but you can add new items. To add
one item to a set use the add() method.
Ex: Add an item to a set, using the add() method:
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
d. Update – The object in the update() method does not have be a set, it can be any iterable
object (tuples, lists, dictionaries et,).
Ex: thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]
thisset.update(mylist)
print(thisset)
e. To remove an item in a set, use the remove(), or the discard() method.
Ex: thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
If the item to remove does not exist, remove() will raise an error.
Ex: thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
If the item to remove does not exist, discard() will NOT raise an error.
Lambda Functions - we use the lambda keyword to declare an anonymous function, which is why we
refer to them as "lambda functions“. An anonymous function refers to a function declared with no
name. Although syntactically they look different, lambda functions behave in the same way as regular
functions that are declared using the def keyword.
• The following are the characteristics of Python lambda functions:
– A lambda function can take any number of arguments, but they contain only a single
expression. An expression is a piece of code executed by the lambda function, which
may or may not return any value.
– Lambda functions can be used to return function objects.
– Syntactically, lambda functions are restricted to only a single expression.
• Creating a Lambda Function
– lambda argument(s): expression
Ex: remainder = lambda num: num % 2 print(remainder(5))
Ex: x = lambda a:a+10
print(x(5))
Ex:x = lambda a,b:a*b
print(x(4,5))