UNIT III
Python Lists
The list is the most fundamental data structure in Python. Because
the index of the first element of the list is zero, the index of the
second element is one, and so on, the list is similar to an array in
C, C++, or Java. The list, on the other hand, is a collection of
disparate data elements. That is, a list can contain both numeric
and character data.
Lists can be used to perform a variety of operations. Indexing,
slicing, adding, multiplying, and checking for membership are
some examples. In the following sections, we will illustrate all of
these operations. Aside from that, the Python language has a
number of built-in functions that we will go over.
Creating a List
In Python, a list is created by placing elements inside square brackets [ ] separated by
commas.
For example, to create a list of integers:
Traversing a List
In Python, you can traverse a list using a for loop. Here is an example of how to use a
for loop to print out each element in a list:
Program to print each element of a list using for loop.
The above code will output:
Indexing
In Python, indexing is used to access elements of a data structure, such
as a list or string, by specifying a numerical position or index. The first
element in a data structure has an index of 0, the second element has an
index of 1, and so on.
mylist[0]
You can also use slicing to access a range of elements in a data structure.
The syntax for slicing is as follows:
mylist[start:end]
This will return a new list containing all elements from the start index
(inclusive) to the end index (exclusive).
Negative Indexing
In Python, negative indexing is a way to access elements of a data
structure, such as a list or string, by specifying a negative numerical
position or index. The last element in a data structure has an index of -
1, the second to last element has an index of -2, and so on.
For example, to access the last element in “mylist”, you would use the code:
mylist[-1]
To access element from a list using negative indexing.
To access the second to last element of a string:
Slicing
In Python, “slicing” is a way to extract a portion of a sequence (e.g. a
string, list, or tuple) by specifying two indices, a start index and an
end index, separated by a colon. The slice will include all elements
from the start index up to, but not including, the end index. For
example, if we have a list called my_list, we can extract the second
through fourth elements
Changing or Adding Elements to a List There are several ways to change
or add elements to a list in Python.
Using the extend() method: This method is used to add multiple elements to a
list. It takes an iterable as an argument and adds each element of that iterable to
the list.
List Methods
In Python, a list is a built-in data type that has a number of useful built-in methods
for working with its elements. Here are some commonly used list methods:
List Functions
Here is a table that summarizes some of the commonly used list functions in
Python:
Implementation of Stacks using Lists
• The list methods make it very easy to use a list as a stack ,where the last
item added is the first item retrieved (“last-in, first-out”).
• To add an item to the top of the stack, use the append() method.
• To retrieve an item from the top of the stack, use pop() without an
explicit index. Set the stack size to three.
• The function display_stack_items() displays current items in the stack.
• The function push_item_to_stack() is used to push an item to stack if
the total length of the stack is less than the stack size else display
“Stack is full” message.
• The function pop_item_from_stack() pops an item from the stack if
the stack is not empty else display “Stack is empty” message .
Implementation of Queues using Lists
• It is also possible to use a list as a queue, where the first item
added is the first item retrieved (“first-in, first-out”).
However, lists are not effective for this purpose.
• While appends and pops are fast from the end of the list, doing
inserts or pops from the beginning of a list is slow because all of
the other items have to be shifted by one.
• To implement a queue , use collections.deque which was
designed to have fast appends and pops from both ends.
Nested Lists
A list inside another list is called a nested list and you can get the
behavior of nested lists in Python by storing lists within the elements of
another list. You can traverse through the items of nested lists using the
for loop.
Python Dictionary
In Python, a dictionary is a built-in data structure that stores key-
value pairs, where each key is unique. Dictionaries are mutable,
which means that you can add, remove, or modify elements after the
dictionary has been created.
Dictionary Properties
•A Python dictionary consists of a key and then an associated value.
•Duplicate keys are not allowed but values can be duplicated.
•Heterogeneous objects are allowed for both keys and values.
•Dictionaries are mutable(can change or update values).
•Indexing and slicing concepts are not applicable.
Python dictionaries offer several advantages:
•Fast Access:
Dictionaries provide near-constant time lookups regardless of the
dictionary's size, making them very efficient for retrieving values
based on keys.
•Flexibility:
Dictionaries can store any type of data as values and use any
hashable type as keys, including numbers, strings, tuples, and more.
•Dynamic Size:
Dictionaries can grow or shrink dynamically as needed, allowing
for efficient memory usage.
•Ease of Use:
Dictionaries have a simple syntax for creating, accessing, and
modifying data, making them intuitive to use.
•Iteration:
You can easily iterate over the keys, values, or key-value pairs of a
dictionary.
•Wide Range of Applications:
Dictionaries are versatile and can be used for various purposes, such
as representing data structures like JSON objects, implementing
caches, counting occurrences, and more.
Creating a Dictionary Dictionaries are defined using curly braces {} or the built-
in dict() function.
Here’s an example of how to create a dictionary:
In this example, the dictionary “person” contains three key-value
pairs: “name” is the key and “John” is the value, “age” is the key
and 30 is the value, and “city” is the key and “New York” is the
value.
Accessing a Dictionary
In Python, a dictionary is a collection of key-value pairs, where each key is
unique. To access a value in a dictionary, you can use the key in square
brackets [] after the dictionary variable name. For example, if you have a
dictionary called “my_dict” with a key “name” and a value “John”, you can
access the value like this:
You can also use the get() method to access a value. This method takes a key as
an argument and returns the value for that key if it exists in the dictionary,
otherwise it returns None (or a default value if specified). For example:
If you want to check if a key is present in the dictionary or not, you can
use the in keyword. For example:
It will return “name key found”
Updating a Dictionary
In Python, you can update the values of a dictionary by using the key
in square brackets [] after the dictionary variable name, and
assigning a new value to it. For example, if you have a dictionary
called “my_dict” with a key “name” and a value “John”, you can
update the value like this:
You can also use the update() method to update multiple key-value
pairs in a dictionary at once. This method takes another dictionary as
an argument and adds its key-value pairs to the original dictionary.
For example:
It will add the key “address” to the dictionary with value “NYC”
Removing or Deleting Elements of a Dictionary
In Python, you can remove or delete elements from a dictionary using the
following methods:
1. The del keyword: You can use the del keyword to remove a specific key-
value pair from a dictionary. For example:
2. The pop() method: The pop() method removes a specific key-value pair
from a dictionary and returns its value. If the key is not found in the dictionary,
it raises a KeyError exception. For example:
Python Dictionary Methods
Python’s built-in dictionary data type provides several methods that
can be used to manipulate dictionaries. Here are some of the most
commonly used dictionary methods:
Python Dictionary Functions
In addition to the methods that can be used to manipulate dictionaries,
Python also provides several built-in functions that can be used to
work with dictionaries.
Python Tuples
In Python, a tuple is a collection of ordered, immutable elements. Tuples are
defined using parentheses, with elements separated by commas. For example, a
tuple containing the integers 1, 2, and 3 would be written as (1, 2, 3).
Tuples can contain elements of different types, such as integers, strings, and
other objects. Because tuples are immutable, their elements cannot be modified
once they are created. However, elements within a tuple can be accessed by
their index, just like a list. Tuples are often used to store related pieces of data,
such as a name and an age.
Creating a Tuple
In Python, a tuple can be created by placing elements inside parentheses,
separated by commas. For example:
Traversing Elements in a Tuple
There are several ways to traverse the elements in a tuple:
1. Using a for loop: You can use a for loop to iterate through the elements in a
tuple. For example:
2. Using the tuple() function: The tuple() function allows you to access the
elements of a tuple by index. For example:
3. Using the enumerate() function: The enumerate() function allows you to access
both the index and the value of each element in a tuple. For example:
4. Using list comprehension :
Indexing
In Python, indexing refers to the process of accessing individual elements of a
data structure, such as a list, tuple, or string. These data structures are indexed
using square brackets [], with the index starting at 0 for the first element. For
example, if you have a list of numbers called “numbers” and you want to access
the first element, you would use the following syntax:
numbers[0]
Negative Indexing
In Python, negative indexing allows you to access elements in a list or array by
counting from the end of the list or array, rather than the beginning. For example,
if you have a list called my_list and you want to access the last element of the
list, you can use the index -1 to do so: my_list[-1]. Similarly, you can use -2 to
access the second to last element, -3 to access the third to last element, and so on.
Tuple Slicing
In Python, tuple slicing allows you to access a range of elements in a tuple by
specifying a start and stop index, separated by a colon. For example, if you have a
tuple called my_tuple and you want to access the second and third elements of the
tuple, you can use the slice my_tuple[1:3]. This will return a new tuple containing
the second and third elements of the original tuple.
Changing/Updating a Tuple
In Python, tuples are immutable, which means that their elements cannot be
modified once they are created. However, you can create a new tuple with the
desired elements, and then reassign it to the same variable, effectively updating the
tuple.
For example, if you want to change the second element of a tuple called my_tuple
from 2 to 10, you would create a new tuple with the desired elements, and then
reassign it to my_tuple
Deleting a Tuple
In Python, you can delete a tuple by using the del statement and specifying the
tuple variable that you want to delete. For example, if you have a tuple called
my_tuple and you want to delete it
As you can see, after the tuple is deleted, trying to access it will result in a
“NameError: name ‘my_tuple’ is not defined” because my_tuple variable no
longer exists.
It’s important to note that once a tuple is deleted, it cannot be accessed or used
again. Also, deleting a tuple does not remove its elements from memory, only the
variable that refers to the tuple is deleted.
Python Tuple Methods
Here is a table that lists some of the most commonly used Python tuple methods
Note that this is not an exhaustive list of tuple methods, there are more
methods that can be used with tuples like max(), min(), sorted() etc.
Python Tuple Functions
Advantages of Tuple
There are several advantages to using tuples in Python:
1. Performance: Tuples are faster than lists because they are
immutable and require less memory.
2. Immutable: Because tuples are immutable, they are safe to use as
keys in a dictionary or as elements of a set, whereas lists cannot be used
as keys in a dictionary or as elements of a set.
3. Safety: Tuples provide a way to separate and store related data that
should not be modified. For example, you can use a tuple to store the x
and y coordinates of a point, and be sure that the values won’t change
accidentally.
4. Readability: Tuples can make code more readable by allowing
you to group related data together. This makes it easy to understand
the meaning of the data and what it represents.
5. Easy to use: Tuples are easy to create and use. They have a
simple syntax and can be created with or without parentheses.
6. Iterable: Tuples are iterable which means you can iterate over the
elements of a tuple using a for loop.
7. Return multiple values: Tuples can be used to return multiple
values from a function, which is more efficient than using a data
structure like a list or dictionary.
Python Sets
In Python, a set is a collection of unique elements. Sets are defined using curly
braces {} or the set() function.
To create a set in Python:
• Sets are unordered, which means that the elements in a set have
no specific order.
• Sets are also mutable, which means that you can add, remove,
and update elements in a set after it is created.
• For example, you can use the add() method to add an element to
a set,
the remove() method to remove an element from a set,
and the update() method to add multiple elements to a set at once.
Sets also support mathematical set operations like union, intersection and
difference.
Changing/Adding Elements to a Set
In Python, sets are mutable, meaning that elements can be added or removed
from a set after it is created. To add an element to a set, use the add() method.
For example:
This will add the element 4 to the set my_set.
To add multiple elements to a set at once, use the update() method. This method
can take any iterable, such as a list or another set, as an argument. For example:
Removing Elements from a Set
To remove an element from a set, use the remove() method. If the element is not
present in the set, a KeyError will be raised.
For example:
This will remove the element 2 from the set my_set.
Alternatively, you can use the discard() method to remove an element from a set.
This method does not raise an error if the element is not present in the set.
This will not raise any error, as 4 is not in the set
my_set
Python Set Operations
In Python, sets are a built-in data type that can be used to store a collection of
unique elements. The following are some common set operations that can be
performed in Python:
1. Union: The union of two sets returns a new set that contains all the elements
from both sets. The union operation is performed using the | operator or the
union() method.
2. Intersection: The intersection of two sets returns a new set that contains only
the elements that are common to both sets. The intersection operation is
performed using the & operator or the intersection() method.
3. Difference: The difference of two sets returns a new set that contains the
elements that are in the first set but not in the second set. The difference
operation is performed using the - operator or the difference() method.
4. Symmetric Difference: The symmetric difference of two sets returns a
new set that contains elements that are in either of the sets but not in both.
The symmetric difference operation is performed using the ^ operator or the
symmetric_difference() method.
5. Subset: To check if a set is a subset of another set, you can use the <=
operator or the issubset() method.
6. Superset: To check if a set is a superset of another set, you can use the >=
operator or the issuperset() method.
The in Operator
In Python, the in operator is used to check if an element is present in a
sequence, such as a list, tuple, set, or string. The in operator returns a Boolean
value indicating whether the element is found in the sequence. For example, if
you have a list of numbers called numbers and you want to check if the number
5 is in the list, you can use the in operator like shown in below.
Python Set Functions
In Python, the built-in set functions are used to perform various operations on
sets, such as checking if all elements meet a certain condition, finding the
number of elements in a set, or finding the maximum or minimum element in a
set. These functions can be used on any iterable, which includes lists, tuples,
and sets. Here are some examples of how you can use the built-in set functions
in a Python program:
Frozen Sets
In Python, a frozen set is a built-in immutable set data type. This means that once
a frozen set is created, its elements cannot be added, removed or modified. Frozen
sets are defined using the frozenset() built-in function or by using curly braces
with a ‘f’ prefix. A frozen set can be useful in situations where you want to use a
set as a key in a dictionary or as an element in another set, but you don’t want the
set to be modified.