0% found this document useful (0 votes)
22 views

Python Unit2

This document summarizes 4 collection data types in Python: tuples, lists, dictionaries, and sets. Tuples are ordered and immutable collections. Lists are ordered and mutable collections that can contain duplicate elements. Dictionaries are unordered collections of key-value pairs where keys must be unique and immutable. Sets are unordered collections that cannot contain duplicate elements. Each data type supports various operations like creation, accessing/updating elements, slicing, deletion, etc.

Uploaded by

kartik i
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Python Unit2

This document summarizes 4 collection data types in Python: tuples, lists, dictionaries, and sets. Tuples are ordered and immutable collections. Lists are ordered and mutable collections that can contain duplicate elements. Dictionaries are unordered collections of key-value pairs where keys must be unique and immutable. Sets are unordered collections that cannot contain duplicate elements. Each data type supports various operations like creation, accessing/updating elements, slicing, deletion, etc.

Uploaded by

kartik i
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

UNIT 2 -Structured Types, Mutability and Higher-Order Functions

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:

1. Tuple is a collection which is ordered and immutable/unchangeable. Allows duplicate


members. The elements of a tuple need not be characters. The individual elements can be of
any type, and need not be of the same type as each other. Literals of type tuple are written
by enclosing a comma-separated list of elements within parentheses. For example, we can
write
Ex:t1 = ()
t2 = (1, 'two', 3)
print t1 #prints empty tuple t1
print t2 #prints tuple t2 with mixed values

The following operations can be performed on a tuple


a) Create tuples – Tuples can be created in the following manner.
Ex: thistuple = ("apple", "banana", "cherry")
print(thistuple)

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

# Printing first Tuple


print("Tuple 1: ")
print(Tuple1)

# Printing Second Tuple


print("\nTuple2: ")
print(Tuple2)

# Printing Final Tuple


print("\nTuples after Concatenaton: ")
print(Tuple3)

d) Delete Tuple Elements


Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple
completely. The del keyword can delete the tuple completely:
Ex: thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists

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]

# list with mixed data types


my_list = [1, "Hello", 3.4]

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']

# elements 3rd to 5th


print(my_list[2:5])
# elements beginning to 4th
print(my_list[:-5])
# elements 6th to end
print(my_list[5:])
# elements beginning to end
print(my_list[:])

c) Update - # Correcting mistake values in a list


odd = [2, 4, 6, 8]
change the 1st item
odd[0] = 1
print(odd)
# change 2nd to 4th items
odd[1:4] = [3, 5, 7]
print(odd)

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()

3. Dictionary - A dictionary is a collection of elements which is unordered, changeable and


indexed. In Python dictionaries are written with curly brackets They have keys and values.
In other words, a dictionary is the collection of key-value pairs where the value can be any
python object whereas the keys are the immutable python object, i.e., Numbers, string or
tuple. Dictionary is an unordered collection of items. The following operations can be
performed on a list:
a) Create – While the values can be of any data type and can repeat, keys must be of immutable
type (string, number or tuple with immutable elements) and must be unique.
Ex: # empty dictionary
my_dict = {}

# dictionary with integer keys


my_dict = {1: 'apple', 2: 'ball'}

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'))

# Trying to access keys which doesn't exist throws error


# Output None
print(my_dict.get('address'))

# 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'

# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}


print(my_dict)

# add item
my_dict['address'] = 'Downtown'

# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}


print(my_dict)

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

The clear() keyword empties the dictionary


Ex: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(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)

myset = {"apple", "banana", "cherry"}

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)

Ex: Check if "banana" is present in the set:


thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)

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))

You might also like