Unit 3
Unit 3
we will discuss the Data Structures in the Python Programming Language and how they are related to
some specific Python Data Types. We will discuss all the in-built data structures like list tuples,
dictionaries, etc.
Lists
Python Lists are just like the arrays, declared in other languages which is an ordered collection of data. It
is very flexible as the items in a list do not need to be of the same type.
The implementation of Python List is similar to Vectors in C++ or ArrayList in JAVA. The costly
operation is inserting or deleting the element from the beginning of the List as all the elements are needed
to be shifted. Insertion and deletion at the end of the list can also become costly in the case where the
preallocated memory becomes full.
Dictionary
Python dictionary is like hash tables in any other language with the time complexity of O(1). It is an
unordered collection of data values, used to store data values like a map, which, unlike other Data Types
that hold only a single value as an element, Dictionary holds the key:value pair. Key-value is provided in
the dictionary to make it more optimized.
Tuple
Python Tuple is a collection of Python objects much like a list but Tuples are immutable in nature i.e. the
elements in the tuple cannot be added or removed once created. Just like a List, a Tuple can also contain
elements of various types.
In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or without the
use of parentheses for grouping of the data sequence.
Set
Python Set is an unordered collection of data that is mutable and does not allow any duplicate element.
Sets are basically used to include membership testing and eliminating duplicate entries. The data structure
used in this is Hashing, a popular technique to perform insertion, deletion, and traversal in O(1) on
average.
String
Python Strings are arrays of bytes representing Unicode characters. In simpler terms, a string is an
immutable array of characters. Python does not have a character data type, a single character is simply a
string with a length of 1.
Below, we’ve explained all the Python list methods you can use with Python lists, for example, append(),
copy(), insert(), and more.
Let’s look at some different list methods in Python for Python lists:
In Python, list slicing is a common practice and it is the most used technique for programmers to solve
efficient problems. Consider a Python list, in order to access a range of elements in a list, you need to
slice a list. One way to do this is to use the simple slicing operator i.e. colon(:). With this operator, one
can specify where to start the slicing, where to end, and specify the step. List slicing returns a new list
from the existing list.
Python List Slicing Syntax
Positive Indexes
In the case of Positive Indexing, the first element of the list has the index number 0, and the last element
of the list has the index number N-1, where N is the total number of elements in the list (size of the list).
Example:
# Initialize list
Lst = [50, 70, 30, 20, 90, 10, 50]
# Display list
print(Lst[::])
Output:
[50, 70, 30, 20, 90, 10, 50]
Negative Indexes
The below diagram illustrates a list along with its negative indexes. Index -1 represents the last element
and -N represents the first element of the list, where N is the length of the list.
Example:
# Initialize list
Lst = [50, 70, 30, 20, 90, 10, 50]
# Display list
print(Lst[-7::1])
Output:
[50, 70, 30, 20, 90, 10, 50]
The clear() method in Python is a built-in method that is used to remove all the elements (key-value pairs)
from a dictionary. It essentially empties the dictionary, leaving it with no key-value pairs.
my_dict = {'1': 'name', '2': 'age', '3': 'class'}
my_dict.clear()
print(my_dict)
Output
{}
2. Dictionary get() Method
In Python, the get() method is a pre-built dictionary function that enables you to obtain the value linked to
a particular key in a dictionary. It is a secure method to access dictionary values without causing a
KeyError if the key isn’t present.
Example:
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
print(d.get('Name'))
print(d.get('Gender'))
Output:
Ram
None
Output
['Name', 'Age', 'Country']
Output
['Ram', '19', 'India']
Output
{'Name': 'Ram', 'Country': 'India'}
Output
{'Name': 'Ram', 'Age': '19'}
{'Name': 'Ram'}
The below Python functions are used to change the case of the strings. Let’s look at some Python string
methods with examples:
lower(): Converts all uppercase characters in a string into lowercase
upper(): Converts all lowercase characters in a string into uppercase
title(): Convert string to title case
swapcase(): Swap the cases of all characters in a string
capitalize(): Convert the first character of a string to uppercase
Python Functions
Python Functions is a block of statements that return the specific task. The idea is to put some commonly
or repeatedly done tasks together and make a function so that instead of writing the same code again and
again for different inputs, we can do the function calls to reuse code contained in it over and over again.
Some Benefits of Using Functions
Increase Code Readability
Increase Code Reusability
Python Function Declaration
The syntax to declare a function is:
we will create a simple function in Python to check whether the number passed as an argument to the
function is even or odd.
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
Default argument
Keyword arguments (named arguments)
Positional arguments
Arbitrary arguments (variable-length arguments *args and **kwargs)
Default Arguments
A default argument is a parameter that assumes a default value if a value is not provided in the function
call for that argument. The following example illustrates Default arguments to write functions in Python.
Keyword Arguments
The idea is to allow the caller to specify the argument name with values so that the caller does not need to
remember the order of parameters.
Positional Arguments
We used the Position argument during the function call so that the first argument (or value) is assigned to
name and the second argument (or value) is assigned to age. By changing the position, or if you forget the
order of the positions, the values can be used in the wrong places,