0% found this document useful (0 votes)
0 views17 pages

Unit+2+ +Data+Structures+in+Python

This document serves as supplementary learning material for a Python for Data Science course, focusing on data structures in Python. It covers key concepts such as variables, operators, lists, tuples, sets, and dictionaries, detailing their definitions, functions, and differences. The document emphasizes the importance of understanding these data structures for efficient data manipulation and storage.

Uploaded by

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

Unit+2+ +Data+Structures+in+Python

This document serves as supplementary learning material for a Python for Data Science course, focusing on data structures in Python. It covers key concepts such as variables, operators, lists, tuples, sets, and dictionaries, detailing their definitions, functions, and differences. The document emphasizes the importance of understanding these data structures for efficient data manipulation and storage.

Uploaded by

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

Supplementary Learning Material

saadsheriff1895@gmail.com
J732KOTCSB

Program: MCA
Specialization: Data Science
Semester: 2
Course Name: Python for Data Science
Course Code: 21VMT5S204
Unit Name: Data Structures in Python

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.

This file is meant for personal use by saadsheriff1895@gmail.com only.


Sharing or publishing the contents in part or full is liable for legal action.
Unit 2
Data Structures in Python
Overview:
Data structures are built-in structures in python that help categorize data which aides in its
storage and manipulation. They help to know if operations can be performed on the data. In
easy terms, they are like shelves. Every shelf has certain type of data that has a purpose and
is organised in a manner that helps for it to be used efficiently. There are 4 basic data
structures in Python, namely Lists, Tuples, Dictionaries and Sets.
These data structures can be differentiated based on their mutability. Mutability is the
ability of changing the internal state of an object in python. Objects whose state cannot be
changed are called immutable objects.

Learning Objectives:
1. Variables:
- What are variables?
- Types of variables
2. Operators:
- What are operators?
saadsheriff1895@gmail.com
- Different types of operators- arithmetic, logical, assignment, comparison,
J732KOTCSB
identity, and bitwise.
3. Lists:
- Defining lists
- Adding, deleting, duplicating lists, and other functions of lists.
- Slicing in lists.
4. Tuples:
- Defining tuples.
- Various functions in tuples
- Discussing the difference between tuples and lists.
5. Sets:
- Defining sets.
- Functions of sets.
6. Dictionaries:
- Defining dictionaries
- Functions of dictionaries
7. Converting from one data structure to another.

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.

This file is meant for personal use by saadsheriff1895@gmail.com only.


Sharing or publishing the contents in part or full is liable for legal action.
What are variables?
A reserved memory location used to store a particular value is called a variable. Variables
are used when the values keep on changing or are not constant. Values that are given to the
computer processor to perform various operations are called variables.

Conventionally, every programming language follows one amongst the following type cases:
1. snake_case: it is a naming type where every word is separated by an underscore.
Ex- shoe_color, city_location
2. camelCase: naming type where the first word is in lowercase and the initial of every
new word is in uppercase. Ex- shoeColor, cityLocation
3. PascalCase: it is a naming type in which the initial of every word is in uppercase and
all other characters are in lowercase. Ex- ShoeColor, CityLocation.
Usually, in python, for variable names snake case is used. However, it must be noted that it
is a convention, meaning people over the world use snake_case, but it is not a compulsion.
Although, one can name a variable in whichever way they see fit, there are some rules
that are followed while naming variables:
1. Variable names are case sensitive. Therefore, apple and Apple are treated as two
different variables.
saadsheriff1895@gmail.com
2. The name of a variable must start with alphabets ( a-z in lowercase or uppercase) or
J732KOTCSB
underscore ( _ ). For ex- alpha, Alpha, _alpha
3. Special characters like +, - , * , /, etc. are not allowed while naming variables.
4. Variable names cannot begin with a number. Ex- 1Alpha will not be a valid variable
name.
5. Python keywords cannot be used as variable names. Keywords include break,
continue, end, etc.

Keywords are specially reserved words in python. These keywords have a specific function.
For instance, the ‘end’ keyword is used at the end of a loop to break the cycle of iterations,
likewise, ‘break’ is used in situations when the desired output is obtained and the loop is to
be stopped.

Operators:
Operators are symbols that carry out arithmetic and logical calculation. So all variables and
numbers are operands and the symbols are operators.
Types of operators:
1. Arithmetic operators: these are used to perform basic mathematical operations.

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.

This file is meant for personal use by saadsheriff1895@gmail.com only.


Sharing or publishing the contents in part or full is liable for legal action.
Operator Function Example
+ Addition c+d
- Subtraction c–d
* Multiplication c*d
/ Division c/d
% Modulus- gives the c%d
remainder of a division
problem
// Floor division- gives the c // d
quotient without the
decimals.
** Exponential- raised to the c ** y
power

An example of each is given below:

saadsheriff1895@gmail.com
J732KOTCSB

2. Assignment operators: operators used to assign values to variables are called


assignment operators.

Operator Function Example


= assignment box = 5
-= Subtraction, equivalent to c-d box -= 2
= > box = box -2
+= Addition, equivalent to c+d Box +=2
= > box=box+2
*= Multiplication, equivalent to c*d Box *=2
= > box=box*2
/= Division, equivalent to c/d Box /=2
= > box=box/2
%= Modulus- gives the remainder of box % =2
a division problem = > box = box % 2

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.

This file is meant for personal use by saadsheriff1895@gmail.com only.


Sharing or publishing the contents in part or full is liable for legal action.
//= Floor division- gives the quotient box //= 2
without the decimals. = > box = box // 2
**= Exponential- raised to the power Box **=2
= > box ** 2

An example of each is given below:

saadsheriff1895@gmail.com
J732KOTCSB

3. Comparison operators: as the name suggests these operators are used for
comparison of two variables or values. Returns Boolean values.
Operator Function Example
== Equal to c == d
!= Not equal to c != d
> Greater than c>d
< Less than c<d
>= Greater than equal to c >= d
<= Less than equal to c <= d

An example of each is given below:

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.

This file is meant for personal use by saadsheriff1895@gmail.com only.


Sharing or publishing the contents in part or full is liable for legal action.
4. Logical operators: they are used to compare two conditional statements. Returns
Boolean values.

Operator Function Example


And If both conditions are true, c > d and c > e
saadsheriff1895@gmail.com returns True
J732KOTCSB
Or If either one of the conditions c > d or c > e
are true, then returns True
Not If c>d

An example of each is given below:

5. Identity Operators: they are used to compare two objects, if they are infact the same
object or not.

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.

This file is meant for personal use by saadsheriff1895@gmail.com only.


Sharing or publishing the contents in part or full is liable for legal action.
Operator Function Example
is If both objects are the same, c is d
returns True
is not If both objects are different, c is not d
then returns True

An example of each is given below:

saadsheriff1895@gmail.com
J732KOTCSBDeclaring a variable:

To declare a variable, type a variable name and then assign a value to it. When you print the
variable name, it displays the value stored inside the variable.

Casting of Variables: to specify the type of data being used is called casting of a variable.

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.

This file is meant for personal use by saadsheriff1895@gmail.com only.


Sharing or publishing the contents in part or full is liable for legal action.
Datatypes of variables:
Python datatypes are divided into two parts: Primitive datatypes and non primitive
datatypes. Pre-defined data types in python are called primitive data types. Examples of
primitive datatypes are int, float, strings. Non-primitive are those that are made by deriving
primitive data types and are user-defined. Examples of non-primitive datatypes are tuple,
list, dictionary and set.
1. Numeric:
they store numeric values. Supported numeric data types in Python:
i. int - integer value datatype. They can be positive, negative or zero. They are whole
saadsheriff1895@gmail.com
J732KOTCSB
numbers.
ii. float - decimal point value datatypes. Fractions are represented by the float type.

2. Boolean:
Boolean type of data stores only two values- True and False. It is also
interchangeably used with 0 and 1.

3. Strings: store string/text values. They are enclosed within double quotes or single
quotes.
Examples of primitive data type:

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.

This file is meant for personal use by saadsheriff1895@gmail.com only.


Sharing or publishing the contents in part or full is liable for legal action.
4. Lists:
Lists are data structures that help to store multiple items in one variable. Lists are mutable
in nature. Which means its structure and order can be changed. The data type of elements
can be any, ie, integer, float, Boolean, etc.
To create lists, we use square brackets. Example:

All elements inside the list are indexed. Indexing in python starts from 0. Therefore, “Alpha”
in the above example has the index 0 in variable “letters”, while the position of “gamma” is
2.
To view a particular element from the list use the index number along with variable name
while displaying it.

saadsheriff1895@gmail.com
J732KOTCSBSince lists are mutable, we can add, delete, duplicate and change list elements.

#1. To add elements:


The .append() function adds elements to the end of the list.

#2. To add an element at a specific position:


The .insert() function is used to add elements at a specific position in the list.

#3. To delete elements:


The .clear() function removes all elements from the list.

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.

This file is meant for personal use by saadsheriff1895@gmail.com only.


Sharing or publishing the contents in part or full is liable for legal action.
Similarly, the .pop() function deletes elements by position.

Lists are indexed so they can have duplicate values. A few other functions of lists include:
len() – displays the length of the list.
type() – displays the variable datatype.
sort() – displays the list in ascending order.
reverse() – reverses the order of the list
copy() – creates a duplicate of a specific element or series of elements.
count() – counts the number of elements inside the list, etc.

Slicing in lists:
If you want to get, say, all the elements beginning from the 3rd until the end, then you can
slice the list.
Using slicing you can specify the index range, the
saadsheriff1895@gmail.com point where you want to begin until the
J732KOTCSBend.
For instance, if you want to display 1 to 10 in a list of 1 to 100 elements, then:

To print all numbers from 90 until the end:

5. Tuples:
Tuples are another type of data structures that are used to store multiple items in one
variable. Unlike lists, tuples are immutable, i.e. they cannot be changed. Tuples are also
ordered. They cannot be shuffled neither can the positions of items inside a tuple be
changed. The way we used [] to create lists, here, we use (). For instance:

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.

This file is meant for personal use by saadsheriff1895@gmail.com only.


Sharing or publishing the contents in part or full is liable for legal action.
A list can be converted into a tuple. Simply enclose the list variable name inside tuple().
Example:

Tuples also have a lot of functions, a few amongst them are:


#1. max() – returns the element that has the maximum value in the tuple.
#2. min() – returns the element that has the minimum value in the tuple.
#3. len() – returns the length of the tuple.
#4. type() – returns the datatype of the variable, in this case, tuple.
Slicing can be used to display part of all the elements of the tuple.

saadsheriff1895@gmail.com
J732KOTCSB

All of these functions look very similar to Lists’. So how are these two different you might
ask?
The main difference is that tuples take up less memory than lists do. Hence, tuples are
faster to execute. They are immutable unlike lists. Lists can easily be reordered, while tuples
cannot. And the easiest difference to identify between them is the type of bracket usage.
Lists use [] while tuples use ().
One must use tuples when they are sure of the order of items, and when they are certain
that items would not be changed. Lists, however, due to their ease of editability can be used
when the elements need to be manipulated.

6. Sets:
Sets are the third type of data structures in Python. The key feature of sets is that they are
unordered and unindexed. Like usual math problems, sets are represented inside curly
braces {}. When we say that lists are unordered, we mean that everytime a variable of

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.

This file is meant for personal use by saadsheriff1895@gmail.com only.


Sharing or publishing the contents in part or full is liable for legal action.
datatype set is executed, the order of elements listed can change. For the same reason, they
cannot have duplicates, unlike lists and tuples. Since they are unindexed, you cannot use the
slicing options of python either.
Sets have a lot of functions.
#1. add() – it adds a value to the set.
#2. remove() – removes a specific element from the set.
#3. pop() – removes any element from the set
#4. union() – returns the union, i.e. joins elements of the two sets.
#5. intersection() – returns the intersection of two elements of two sets.
#6. difference() – returns the difference between two sets, i.e. returns A-B for value of A.
#7. symmetric_difference() – returns elements from both sets minus elements common
between the two. In other words, compliment of A intersection B.
An example of each of the above methods is given here:

saadsheriff1895@gmail.com
J732KOTCSB

Apart from the mentioned functions, sets have numerous other functions like .isdisjoint(),
.issubset(), .issuperset(), .update(), etc.
Sets are helpful when you want you require to do mathematical operations like combine or
separate items from two different sets. They help remove duplicity from lists and tuples.
sets are also faster than lists.

7. Dictionary:
Dictionary is a data structure. It is ordered. It cannot be duplicated. It can be
changed, hence, they are mutable. They are written within curly braces. Dictionaries
store data in the key : value format. Every key has a value. Just like indexing, keys
are used to identify values here. They can be used for bivariate data.

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.

This file is meant for personal use by saadsheriff1895@gmail.com only.


Sharing or publishing the contents in part or full is liable for legal action.
For example you have the heights of individuals and the frequency of people of the
the same height. To store these values, you use dictionaries. The height(in inches)
forms the key and the frequency of individuals becomes a value.
Note, one key cannot contain two values.

How is a dictionary different from a list?

A list is collection of values that can be identifies by their indexes. For the same
reason, lists are ordered. However, in case of dictionary, you have ‘key’s that do the
work of indexes. These keys help in identifying values. Thus, the dictionary is not
always ordered. Another important differentiation will be the use of brackets. While
the lists use square brackets [], dictionaries use curly braces {}. Inside a list, every
element is separated by a comma. In dictionaries, a key is written, followed by its
value which is then separated by a comma.
Declaring a dictionary:
To declare a dictionary, you enter the variable name and enter the elements in key:value
form.

saadsheriff1895@gmail.com
J732KOTCSB

To print a specific value, enter the key name after the variable. For example:

To add elements to the dictionary:


Enter dictionary name followed by key name in enclosed square brackets and then enter the
value of the key.

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.

This file is meant for personal use by saadsheriff1895@gmail.com only.


Sharing or publishing the contents in part or full is liable for legal action.
To delete elements from the dictionary:
To delete the last item, the .popitem() function is used.
To delete a specific item, the .pop(‘key_name’) function is used.
To delete all items of the dictionary, the .clear() function is used.

saadsheriff1895@gmail.com
J732KOTCSB

To determine the number of elements in the dictionary:


We use the len() function to determine the number of items inside a dictionary

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.

This file is meant for personal use by saadsheriff1895@gmail.com only.


Sharing or publishing the contents in part or full is liable for legal action.
Other methods of dictionaries:
.get() – gives the value associated with the key name that is mentioned.
.keys() – returns an object containing all the keys of the dictionary.
.values() – returns an object containing all the values of a dictionary.
.items() – returns a tuple for all key:value items.
.update() – returns an object with specified key:value items.
.copy() – returns a copy of the dictionary.

Converting a list to set:


A list can be converted to a set simply by using the set() method. Once done, the output
screen will show the result in curly braces { } instead of square brackets [ ].
saadsheriff1895@gmail.com
J732KOTCSB
Converting a set to list:
A set can be converted to a list simply by using the list() method. Once done, the output
screen will show the result in square brackets [ ] instead of curly braces { }.

Converting a list to tuple


You can use the above method to convert a list into a tuple and vice versa. There is another
approach to get the same output, that is, by using (*list_name, ).

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.

This file is meant for personal use by saadsheriff1895@gmail.com only.


Sharing or publishing the contents in part or full is liable for legal action.
Converting Dictionaries to lists:
The .items() method converts a dictionary to a list of tuples.

saadsheriff1895@gmail.com
J732KOTCSB
Similary, for most part, you can convert one data structure to another easily. It must also be
noted that sometimes loops are also used to convert an object from one data structure to
another.

In a gist:
Category Lists Tuples Sets Dictionaries
Mutability Mutable Immutable Mutable Mutable
Ordered Ordered Ordered Unordered Unordered
Index-access Yes Yes No No
Braces [] () {} {}
Duplicates Can contain Can contain Cannot contain Cannot contain
duplicates duplicates duplicates duplicate keys

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.

This file is meant for personal use by saadsheriff1895@gmail.com only.


Sharing or publishing the contents in part or full is liable for legal action.
Doubts:
In numeric:
iii. long - 32 bit numbers ranging between -2147483648 and +2147483648.
iv. complex - complex numbers having a real part(x) and an imaginary part(y),
represented as (x+yi).
Should I write Bitwise operators
Are dictionaries ordered? Because version 3.6 is ordered, before that unordered.

saadsheriff1895@gmail.com
J732KOTCSB

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.

This file is meant for personal use by saadsheriff1895@gmail.com only.


Sharing or publishing the contents in part or full is liable for legal action.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy