0% found this document useful (0 votes)
3 views7 pages

Unit 3

This document provides an overview of Python data types and structures, including lists, dictionaries, tuples, sets, and strings. It explains their characteristics, methods, and how to manipulate them using various built-in functions. Additionally, it covers Python functions, their declaration, calling, and types of arguments.

Uploaded by

saileshmehra7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views7 pages

Unit 3

This document provides an overview of Python data types and structures, including lists, dictionaries, tuples, sets, and strings. It explains their characteristics, methods, and how to manipulate them using various built-in functions. Additionally, it covers Python functions, their declaration, calling, and types of arguments.

Uploaded by

saileshmehra7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Unit-3

Python Data types


Data Structures are a way of organizing data so that it can be accessed more efficiently depending
upon the situation. Data Structures are fundamentals of any programming language around which a
program is built. Python helps to learn the fundamental of these data structures in a simpler way as
compared to other programming languages.

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.

Python List methods


Python List Methods are the built-in methods in lists used to perform operations on Python lists/arrays.

Below, we’ve explained all the Python list methods you can use with Python lists, for example, append(),
copy(), insert(), and more.

List Methods in Python

Let’s look at some different list methods in Python for Python lists:

S.no Method Description


1 append() Used for adding elements to the end of the List.
2 copy() It returns a shallow copy of a list
3 clear() This method is used for removing all items from thelist.
4 count() These methods count the elements.
5 extend() Adds each element of an iterable to the end of the List.
6 index() Returns the lowest index where the element appears.
7 insert() Inserts a given element at a given index in a list.
8 pop() Removes and returns the last value from the List or the given index value.
9 remove() Removes a given object from the List.
10 reverse() Reverses objects of the List in place.
11 sort() Sort a List in ascending, descending, or user-defined order
12 min() Calculates the minimum of all the elements of the List
13 max() Calculates the maximum of all the elements of the List

Python Tuple methods


S.no Method Description
1 len() It returns the number of elements in a tuple.
2 max() It returns the largest element in a tuple.
3 min() It returns the smallest element in a tuple
4 sum() It returns the sum of all the elements in a tuple.

Python List Slicing

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

Lst[ Initial : End : IndexJump ]

Indexing in Python List


Indexing is a technique for accessing the elements of a Python List. There are various ways by which we
can access an element of a list.

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]

List of Python Dictionary Methods


1. Dictionary clear() Method

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

3. Dictionary keys() Method


The keys() method in Python returns a view object with dictionary keys, allowing efficient access and
iteration.

d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}


print(list(d.keys()))

Output
['Name', 'Age', 'Country']

4. Dictionary values() Method


The values() method in Python returns a view object containing all dictionary values, which can be
accessed and iterated through efficiently.

d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}


print(list(d.values()))

Output
['Ram', '19', 'India']

5. Dictionary update() Method


Python’s update() method is a built-in dictionary function that updates the key-value pairs of a dictionary
using elements from another dictionary or an iterable of key-value pairs. With this method, you can
include new data or merge it with existing dictionary entries.

d1 = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}


d2 = {'Name': 'Neha', 'Age': '22'}
d1.update(d2)
print(d1)
Output
{'Name': 'Neha', 'Age': '22', 'Country': 'India'}

6. Dictionary pop() Method


In Python, the pop() method is a pre-existing dictionary method that removes and retrieves the value
linked with a given key from a dictionary. If the key is not present in the dictionary, you can set an
optional default value to be returned.

d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}


d.pop('Age')
print(d)

Output
{'Name': 'Ram', 'Country': 'India'}

7. Dictionary popitem() Method


In Python, the popitem() method is a dictionary function that eliminates and returns a random (key, value)
pair from the dictionary.
As opposed to the pop() method which gets rid of a particular key-value pair based on a given key,
popitem() takes out and gives back a pair without requiring a key to be specified.

d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}


d.popitem()
print(d)
d.popitem()
print(d)

Output
{'Name': 'Ram', 'Age': '19'}
{'Name': 'Ram'}

Python String Methods


Python string methods is a collection of in-built Python functions that operates on lists.
Note: Every string method in Python does not change the original string instead returns a new string with
the changed attributes.
Python string is a sequence of Unicode characters that is enclosed in quotation marks

Case Changing of Python String Methods

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:

Creating a Function in Python


We can define a function in Python, using the def keyword. We can add any type of functionalities and
properties to it as we require. By the following example, we can understand how to write a function in
Python. In this way we can create Python function definition by using def keyword.

# A simple Python function


def fun():
print("Welcome to Python")

Calling a Function in Python


After creating a function in Python we can call it by using the name of the functions Python followed by
parenthesis containing parameters of that particular function. Below is the example for calling def
function Python.

# A simple Python function


def fun():
print("Welcome to Python")

# Driver code to call a function


fun()

Python Function Arguments


Arguments are the values passed inside the parenthesis of the function. A function can have any number
of arguments separated by a comma.

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

# Driver code to call the function


evenOdd(2)
evenOdd(3)

Types of Python Function Arguments


Python supports various types of arguments that can be passed at the time of the function call. In Python,
we have the following function argument types in Python:

 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,

Arbitrary Keyword Arguments


In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a variable number of arguments
to a function using special symbols. There are two special symbols:

 *args in Python (Non-Keyword Arguments)


 **kwargs in Python (Keyword Arguments)

You might also like