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

3.1_3.2_3.3_3.4 Data Structures in Python

The document provides an overview of data structures in Python, specifically focusing on Lists, Tuples, Sets, and Dictionaries. It explains the characteristics, creation, accessing, updating, and deleting of elements in each data structure, along with examples and built-in methods. The content serves as a comprehensive guide for understanding and utilizing these fundamental data structures in Python programming.

Uploaded by

kirti p
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

3.1_3.2_3.3_3.4 Data Structures in Python

The document provides an overview of data structures in Python, specifically focusing on Lists, Tuples, Sets, and Dictionaries. It explains the characteristics, creation, accessing, updating, and deleting of elements in each data structure, along with examples and built-in methods. The content serves as a comprehensive guide for understanding and utilizing these fundamental data structures in Python programming.

Uploaded by

kirti p
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 60

Data Structures in Python

Ms. G. D. Patne
Lecturer in Computer Engg.
Government Polytechnic Ratnagiri
Content
 Introduction
 Lists
 Tuples
 Sets
 Dictionaries
Introduction
 A data structure is specialized format for organizing and storing data,
so that various operations can be performed on it efficiently and
easily.
 Any data structure is designed to organize data to suit a specific
purpose so that it can be accessed and worked with in appropriate
and systematic manner.
 There are four data structures in Python, List, Tuples, Sets and
Dictionaries.
 A data structure that stored an ordered collection of items in Python is
called a list.
 In other words it holds a sequence of items or elements.
 Similar to a list, the tuple is an ordered sequence of items.
 A set is an unordered collection of unique items in Python.
 A dictionary in Python is an unordered collection of key value pairs.
 The data types that are most used in Python are string, tuples, list and
dictionaries.
Lists
 A list in Python is a linear data structure.
 The elements in the list are stored in a linear order one after
another.
 A list is a collection of elements.
 The element in a list can be accesses by their positions i.e.
indices.
 The index in lists always starts with 0 and ends with n-1, if the list
contains n elements.
 In Python lists are written with square brackets [].
 A list is created by placing all the elements inside a square
brackets, separated by commas.
 Syntax:
<list name>=[value1, value2,….value n]
 Example:
Emp=[20,’amar’, ‘M’, 30]
 List are mutable or changeable.
 The value of any element inside list can be changed at any point of time.
 A list data type is flexible data type that can be modified according to the
requirement.
Creating a List
Accessing value in List
 Accessing elements from a
list in Python programming is
a method to get values that
are stored in the list at a
particular location or index.
 To access values in lists, use
the square brackets for
slicing along with the index
obtained value available at
that index.
 Accessing elements from a
particular list in Python at
once allows the user to
access all the values from
the lists.
 This is possible by writing
the list name in the print()
statement.
 E.g. print(L)
Deleting Values in List
 Python provides many ways in which the elements
in a list can be deleted.
1. pop() method in python is used to remove a
particular element from the given index in the list.
By default it removes and returns the last element
if index is not provided.
2. We can delete one or more elements from
a list using the keyword ‘del’. It can even
delete the list entirely.
But it does not store the value for further
use.
3. The remove() method in Python is used
to remove a particular element from the list.
We use the remove() method if we know the
element that we want to remove or delete
from the list (not index).
Updating Lists
 List are mutable, meaning their element can be changed or updated.
 Mutability is the ability for certain types of data to be changed without entirely
recreating it.
 Using mutable data type can allow programs to operate quickly and efficiently.
 Multiple values can be added into list.
 We can use assignment operator (=) to change an item or a range of items.
 We can update items of the list by simply assigning the value at the particular
index position.
 We can also remove the items from the list using remove() or pop() or del
statement
 List methods used for updating list:
Sr. Method Syntax Argument Return Type
No Description
.
1 append() List.append(item) The item can be Only modifies
numbers, strings, the original
another list, list. It does
dictionary, etc not return any
value
2 extend() List1.extend(list2) Takes a list and Only modifies
adds it to the the original
end list. It doesn’t
return any
value
3 Insert() List.insert(index,eleme This index is It does not
nt) position where return
an element anything:
needs to be returns none
inserted element-
The element to
be inserted in the
list
+ operator
and *
Operator

Sort() method
Basic List Operations
1. Indexing:
 An individual item in the list can be referenced by using an index,
which is an integer number that indicates the relative position of the
item in the list.
 We can use the index operator [] to access an item in a list. Index
start from 0. so a list having 5 elements will have index from 0 to 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.
List Slicing
 Slicing is an operation that allows us to extract elements
from units.
 The slicing feature used by python to obtain a specific subset
or element of the data structure using colon (:) operator.
 Syntax:
› List_var[start_index:end_index]
Will return the subset of the list starting from start_index to on index
less than that of the end index.
List Slicing with step
size:
Traversing a List:
 Traversing a list means accessing all the elements of
the list.
 Traversing can be done by using any conditional
statement of Python, but it is preferable to use for loop.
Built-in Functions and Methods for List:
Sr.No Function with Description
1 cmp(list1, list2)
Compares elements of both lists.

2 len(list)
Gives the total length of the list.p>

3 max(list)
Returns item from the list with max value.

4 min(list)
Returns item from the list with min value.

5 list(seq)
Converts a tuple into list.
6. sum(list)
Calculate sum of all the elements of list.
Methods of List Class:
Sr.No Methods with Description

1 list.append(obj)
Appends object obj to list
2 list.count(obj)
Returns count of how many times obj occurs in list
3 list.extend(seq)
Appends the contents of seq to list
4 list.index(obj)
Returns the lowest index in list that obj appears
5 list.insert(index, obj)
Inserts object obj into list at offset index
6 list.pop(obj=list[-1])
Removes and returns last object or obj from list
7 list.remove(obj)
Removes object obj from list
8 list.reverse()
Reverses objects of list in place
9 list.sort([func])
Sorts objects of list, use compare func if given
Tuples
 A tuple is also a linear data structure.
 A python tuple is a sequence of data values called as
items or elements.
 Each element or value that is inside of tuple is called an
item.
 A tuple is a collection of items which is ordered and
unchangeable.
 A tuple data structure that is immutable means you can
not add and remove items from the tuple..
 Their values cannot be modified.
 A tuple is a heterogeneous data structure and used for
grouping data.
 In python tuples are written with round bracket () and
values in tuples can be accessed by their index values,
which are integer starting from 0.
 Values are separated by comma (,).
Creating Tuple
 To create tuple, all the elements are placed inside parenthesis()
separated by commas and assigne to a variable.
 Syntax:
› <tuple_Name>= (value1, value2,….valuen)
Example: emp=(20,”ABC”,’M’, 30)
 A tuple in Python is immutable data type which means a tuple
once created cannot be modified.
 Tuples can have any number of different data items.
Accessing value in Tuple
 Accessing elements from the tuple is a method to get
values stored in the tuple from a particular location or
index.
Deleting Tuples
 Tuples are unchangeable, so we cannot remove
elements from it., but we can delete the tuple
completely.
 To explicitly remove an entire tuple, just use the
del statement.
Updating Tuple
 Tuple are immutable which means we cannot update or
change the values of tuple element.
 We are also able to take portions of existing tuples to create
new tuples.
Tuple Operations
Built in Functions of Tuple
Sets
 The set data structure in Python programming is implemented
to support mathematical set operations.
 Set is an unordered collection of unique elements.
 Elements stored in a set are not kept in any particular order.
 Sets are unindexed that means we cannot access set elements
by referring to an index.
 Sets are changeable(mutable), i.e we can change a set as and
when required.
 Type of elements in a set need not to be same, various mixed
data type values can also be passed to the set.
 Set operations: Union, Intersection, difference, complement
etc.
 Set is defined by values separated by comma inside curly
brackets { }.
 Syntax:

<set_name>={value1, value2,……, value n}


 Example: emp={20,”ABC”, ‘M’, 31}
Accessing Values in Sets
Deleting Values in Set
1. Remove element from a set by using
discard() method.
2. Remove element from a set by using
remove() method. The only difference
is that if specified element is not
present in set the remove() method
raises KeyError.
3. pop() method removes random
element from a set and return it.
4. clear() method remove all elements
from the set.
Discard

Remove
Pop:

Clear:
Updating Set

1. Using add() method :


 We can add elements to a set by using
add() method.
 The add () method takes one argument
which is the element you want to add in set.
 At a time only one element can be added to
the set by using add() method.
 Loop can be used to add multiple elements
at a time using add() method.
 Syntax: A.add(element)
 Example: a={1,2,3,4}
 A.add(7)
2. Using Update() method:
 The update() adds elements from
lists/strings/tuples sets to the set.
 The update() method can accepts list,
strings, tuples, as well as other sets as its
arguments.
 Duplicate elements are avoided.
 Syntax: A.update(B)
 Example: num={10,20,30,40,50,60,70}
Basic Set Operations
Built in Methods for Set
Function Description

add() Adds an element to a set

Removes an element from a set. If the element is not


remove()
present in the set, raise a KeyError

clear() Removes all elements form a set

copy() Returns a shallow copy of a set

Removes and returns an arbitrary set element. Raise


pop()
KeyError if the set is empty

update() Updates a set with the union of itself and others

union() Returns the union of sets in a new set

difference() Returns the difference of two or more sets as a new set

difference_update() Removes all elements of another set from this set

Removes an element from set if it is a member. (Do


discard()
nothing if the element is not in set)

intersection() Returns the intersection of two sets as a new set

intersection_update() Updates the set with the intersection of itself and another

isdisjoint() Returns True if two sets have a null intersection

issubset() Returns True if another set contains this set

issuperset() Returns True if this set contains another set

symmetric_difference() Returns the symmetric difference of two sets as a new set

Updates a set with the symmetric difference of itself and


symmetric_difference_update()
another
Dictionaries
 The dictionary data structure is used to store key value pairs indexed by
keys.
 A dictionary is an associative data structure, means that elements are
stored in a non linear fashion.
 Python dictionary is an unordered collection of elements.
 Dictionary has a key: value pair.
 Each value is associated with a key.
 Dictionaries are optimized to retrieve values when the key is known.
 A key and its value is separated by colon(:) between them.
 Elements in dictionaries are separated by commas and all elements must be
enclosed in curly brackets.
 Syntax: <dictionary_name>={key1:value1, key2:value2,..}
 Example: emp={“id”:1, “name”:”ABC”, “Salary”:25000}
 A pair of curly bracket with no value is known as empty dictionary.
 Dictionary elements are accessed by keys.
 Values of dictionaries can be duplicated, but the keys in dictionary are
unique.
 Dictionaries are changeable (mutable), i.e. we can change element in
dictionary.
 Dictionary can be nested i.e. a dictionary can contain another dictionary.
Creating Dictionary
 We can create a dictionary by placing a
comma separated list of key:value pairs
in curly bracket.
 Python provides a built in function dict()
for creating a dictionary.
 Example:

1. x = dict(name = "John", age = 36, country =


"Norway")
print(x)
2. X=dict({1:”Orange”, 2:”Mango”,3:”Apple”})
print(x)
3. x=dict([(1,”Red”), (2,”Blue”), (3,”Yellow”)])
print(x)
Accessing Values in Dictionary

 Python dictionary method get() returns a value for the given


key. If key is not available then returns default value None.
 Syntax
 dict.get(key, default = None)
 Example:
 dict = {'Name': 'Zabra', 'Age': 7}
 Output:
 Value : 7
Deleting Elements from Dictionary

 We can remove a particular item in a dictionary by using the method


pop().it reuire at least on argument. it returns value which is removed
from dictonary.
 Popitem() can be used to remove and return an arbitrary element from
the dictionary. it removes last element from dictionary. does not require
any argument.
 This method removes as element with the provided key and return the
value.
 All elements can be removed at once using the clear() method.
 We can also use the del keyword to remove individual items or the
entire dictionary itself.
Updating Dictionary
 The dictionary data type is flexible data type that can be
modified according to the requirements which makes it is a
mutable data type.
 We can add new element or change the value of existing
element using assignment operator.
 If the key is already present, value gets updated, else new
key:value pair is added to the dictionary.
Basic Operation on Dictionary
1. Dictionary membership Test:
 We can test if a key is in a dictionary or not using keyword
‘in’.
 Example:

>>>square={1:1,2:4,3:9,4:16}
print(1 in square)
2. Traversing Dictionary:
 Using for loop we can iterate through each key in dictionary.
 Example:

>>>square={1:1,2:4,3:9,4:16}
>>> for I in square:
print(i,square[i])
Built in Methods for dictionary
Method Description
clear() Removes all items from the dictionary.
copy() Returns a shallow copy of the dictionary.

Returns a new dictionary with keys from seq


fromkeys(seq[, v])
and value equal to v (defaults to None).

Returns the value of the key. If the key does


get(key[,d])
not exist, returns d (defaults to None).

Return a new object of the dictionary's items


items()
in (key, value) format.

keys() Returns a new object of the dictionary's keys.

Removes the item with the key and returns


its value or d if key is not found. If d is not
pop(key[,d])
provided and the key is not found, it raises
KeyError.
Removes and returns an arbitrary item (key,
popitem() value). Raises KeyError if the dictionary is
empty.
Returns the corresponding value if the key is
setdefault(key[,d]) in the dictionary. If not, inserts the key with a
value of d and returns d (defaults to None).

Updates the dictionary with the key/value


update([other])
pairs from other, overwriting existing keys.

Returns a new object of the dictionary's


values()
Built in Functions for Dictionary
Function Description
Return True if all keys of the
all() dictionary are True (or if the
dictionary is empty).
Return True if any key of the
dictionary is true. If the
any()
dictionary is empty, return
False.
Return the length (the
len() number of items) in the
dictionary.
Compares items of two
cmp() dictionaries. (Not available in
Python 3)
Return a new sorted list of
sorted()
keys in the dictionary.
Strings
 A string is a linear data structure in Python.
 Strings are the group of characters.
 Strings start and end with single or double
quotes.
 Python strings are immutable means string can
not be modified according to requirement.
 Example:
>>> a=‘Hello World’
 a
‘’Hello World’
 Str Class:
› Strings are objects of the str class.
› We can create a string using the constructor of str
class.
› Example:
Deleting Entire Strings
 Deletion of entire string is possible with
the use of del keyword.
 Example:
>>>a=‘Python’
>>> a
Python
>>> del a
 + Operator:
 The concatenation operator(+) is
used to join two strings.
 Example:

>>>”Hello”+”Python”
HelloPython
 * Operator:
 The multiplication operator is used to
concatenate the same string multiple times.
It is called repetition operator.
 Example:
>>> s1=“Hello”
>>>s2=3*s1
‘Hello Hello Hello’
 String Traversal:
 Traversal is a process in which we
access all the elements of the string
one by one using for and while loop.
Example:
>>> s=“Welcome”
>>>for c in s:
print(c,end=“”)
 Immutable Strings:
› Strings are immutable means we can not
change any element of a string.
› If we want to change an element of a string,
we have to create a new string.
› Example:
>>> str=“Python”
>>>str[0]=“H”
Error
Use
>>>str1=‘H’+str[1:]
>>>str1
 String Indices and Accessing string
Elements:
 ‘in’ and ‘not in’ operator in Strings:
› The ‘in’ operator is used to check whether
a character or a substring is present in a
string or not.
› The expression returns a Boolean value.
› Example:
>>> s=“Hello”
>>> ‘He’ in s
True
 String Slicing:
› A piece of string is known as slice.
› To cut a substring from string is called string
slicing.
› Slice operator is applied to a string with the
use of square bracket[].
› Ending limit exclude the last index (n-1).
› A slice 3:7 means 3rd, 4th, 5th and 6th position
character.
› Syntax:
 Stringname[start_index:end_index]
 Stringname[start_index:end_index: step_size]
› Example:
 >>>s=“Hello”
 >>>s[0:2]
 he
Special Charctaer in String
String Formatting Operators
Sr.No Format Symbol & Conversion
1 %c character
2 %s string conversion via str() prior to formatting

3 %i signed decimal integer

4 %d signed decimal integer

5 %u unsigned decimal integer

6 %o octal integer

7 %x hexadecimal integer (lowercase letters)

8 %X hexadecimal integer (UPPERcase letters)

9 %e exponential notation (with lowercase 'e')

10 %E exponential notation (with UPPERcase 'E')

11 %f floating point real number

12 %g the shorter of %f and %e

13 %G the shorter of %f and %E


Method Description
capitalize() Converts the first character to upper case

casefold() Converts string into lower case


center() Returns a centered string
count() Returns the number of times a specified value
occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified
value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns
the position of where it was found

format() Formats specified values in a string


format_map() Formats specified values in a string
index() Searches the string for a specified value and returns
the position of where it was found

isalnum() Returns True if all characters in the string are


alphanumeric
isalpha() Returns True if all characters in the string are in the
alphabet
isdecimal() Returns True if all characters in the string are
decimals
isdigit() Returns True if all characters in the string are digits

isidentifier() Returns True if the string is an identifier


islower() Returns True if all characters in the string are lower
case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a
specified value
rfind() Searches the string for a specified value and returns the
last position of where it was found
rindex() Searches the string for a specified value and returns the
last position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a
list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a
list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice
versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the
beginning

You might also like