Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Python Data Structure

The document provides an overview of Python data structures, including lists, sets, tuples, and dictionaries, explaining their characteristics and usage. It details how to create, access, update, and remove items in these data structures, emphasizing the mutable nature of lists and sets, and the immutability of tuples. The document serves as a fundamental guide for understanding and utilizing these essential data structures in Python programming.

Uploaded by

globallandmark11
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)
6 views

Python Data Structure

The document provides an overview of Python data structures, including lists, sets, tuples, and dictionaries, explaining their characteristics and usage. It details how to create, access, update, and remove items in these data structures, emphasizing the mutable nature of lists and sets, and the immutability of tuples. The document serves as a fundamental guide for understanding and utilizing these essential data structures in Python programming.

Uploaded by

globallandmark11
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/ 101

Python Data Structures

Python Data Structures

• 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.
Python Data Structures
Main Types
Types of Python Data Structures:
• Lists
• Sets
• Tuples
• Dictionaries
Python Data Structures
List

• Lists are a type of data structure containing an ordered


collection of items.
• Lists are mutable, allowing elements to be searched,
added, moved and deleted after creation.
• Lists can also be nested, allowing them to contain any
object, including other lists and sublists
Python Data Structures
Creating Python List

• List = [1, 2, 3, "GFG", 2.3]


• print(List)

• list1 = ["Rohan", "Physics", 21, 69.75]


• list2 = [1, 2, 3, 4, 5]
• list3 = ["a", "b", "c", "d"]
• list4 = [25.50, True, -55, 1+2j]
Python Data Structures
Creating Python List
• List elements can be accessed by the assigned index. In python
starting index of the list, sequence is 0 and the ending index is
(if N elements are there) N-1
Python Data Structures
Creating Python List

• To access values in lists, use the square brackets for slicing along
with the index or indices to obtain value available at that index.
• list1 = ['physics', 'chemistry', 1997, 2000];
• list2 = [1, 2, 3, 4, 5, 6, 7 ];
• print ("list1[0]: ", list1[0])
• print ("list2[1:5]: ", list2[1:5])
Python Data Structures
Accessing Python List

• In Python, a list is a sequence of elements or objects, i.e. an


ordered collection of objects.
• Similar to arrays, each element in a list corresponds to an index.
• To access the values within a list, we need to use the square
brackets "[]" notation and, specify the index of the elements
we want to retrieve
Python Data Structures
Accessing Python List
Python Data Structures
Access List Items with Negative
Indexing
• Negative indexing in Python is used to access elements from the
end of a list, with -1 referring to the last element, -2 to the
second last, and so on
Python Data Structures
Access List Items with Slice
Operator

• The slice operator in Python is used to fetch one or more items


from the list. We can access list items with the slice operator by
specifying the range of indices we want to extract
• Syntax:
• start is the starting index (inclusive).
• stop is the ending index (exclusive).
Python Data Structures
Example
Python Data Structures
Updating Lists

• You can update single or multiple elements of lists by giving the


slice on the left-hand side of the assignment operator, and you
can add to elements in a list with the append() method
Python Data Structures
Change a Range of List Items

• You can update single or multiple elements of lists by giving the


slice on the left-hand side of the assignment operator, and you
can add to elements in a list with the append() method
Python Data Structures
Adding List Items Using append()
Method
• The append() method in Python is used to add a
single element to the end of a list.
• We can add list items using the append() method by
specifying the element we want to add within the
parentheses, like my_list.append(new_item), which
adds new_item to the end of my_list
Python Data Structures
Adding List Items Using append()
Method
Python Data Structures
Adding List Items Using insert() Method
• The insert() method in Python is used to add an element at a
specified index (position) within a list, shifting existing
elements to accommodate the new one.
• We can add list items using the insert() method by specifying
the index position where we want to insert the new item and
the item itself within the parentheses,
like my_list.insert(index, new_item).
Python Data Structures
Adding List Items Using extend() Method
• The extend() method in Python is used to add multiple elements
from an iterable (such as another list) to the end of a list.
• We can add list items using the extend() method by passing
another iterable containing the elements we want to add,
like my_list.extend(iterable), which appends each element
from the iterable to the end of my_list.
Python Data Structures
Remove List Item Using remove()
Method
• To remove a list element, you can use either the del statement if
you know exactly which element(s) you are deleting or the
remove() method if you do not know
Python Data Structures
Remove List Item Using pop() Method
• We can remove list items using the pop() method by calling it
without any arguments my_list.pop(), which removes and
returns the last item from my_list, or by providing the index of
the item we want to remove my_list.pop(index), which
removes and returns the item at that index
Remove List Item Using clear()
Method
• The clear() method in Python is used to remove all elements from
a list, leaving it empty.
• We can remove all list items using the clear() method by calling it
on the list object like my_list.clear(), which empties my_list,
leaving it with no elements.
Remove List Item Using del Keyword

• The del keyword in Python is used to delete element either at a


specific index or a slice of indices from memory.
• We can remove list items using the del keyword by specifying the
index or slice of the items we want to delete, like del
my_list[index] to delete a single item or
del my_list[start:stop] to delete a range of items.
Python List Methods
Python List Methods
Built-in Functions with Lists
Python - Tuples

• Tuple is one of the built-in data types in Python. A Python


tuple is a sequence of comma separated items, enclosed in
parentheses (). The items in a Python tuple need not be of
same data type.
Accessing Values in Tuples

To access values in tuple, use the square brackets for slicing along
with the index or indices to obtain value available at that index.
Accessing Tuple Items with Negative
Indexing
• Negative indexing in Python is used to access elements from
the end of a tuple, with -1 referring to the last element, -2 to
the second last, and so on.
• We can also access tuple items with negative indexing by using
negative integers to represent positions from the end of the
tuple.
Accessing Range of Tuple Items
with Negative Indexing
By range of tuple items, we mean accessing a subset of elements
from a tuple using slicing. Therefore, we can access a range of
tuple items with negative indexing by using the slicing operation
in Python.
Access Tuple Items with Slice
Operator

• The slice operator in Python is used to fetch one or more


items from the tuple. We can access tuple items with the slice
operator by specifying the range of indices we want to extract.
• It uses the following syntax:

•start is the starting index (inclusive).


•stop is the ending index (exclusive).
Access Tuple Items with Slice
Operator
Accessing Sub Tuple from a Tuple

• A subtuple is a part of a tuple that consists of a consecutive


sequence of elements from the original tuple.
• We can access a subtuple from a tuple by using the slice
operator with appropriate start and stop indices.
• It uses the following syntax:
•start is the starting index (inclusive).
•stop is the ending index (exclusive) of the subtuple.
Accessing Sub Tuple from a Tuple
Python - Update Tuples

• In Python, tuple is an immutable sequence, meaning once a


tuple is created, its elements cannot be changed, added, or
removed.
• To update a tuple in Python, you can combine various
operations to create a new tuple.
Python - Update Tuples

• For instance, you can concatenate tuples, slice them, or use


tuple unpacking to achieve the desired result.
• This often involves converting the tuple to a list, making the
necessary modifications, and then converting it back to a tuple
Updating Tuples Using Concatenation
Operator

• The concatenation operator in Python, denoted by +, is used to


join two sequences, such as strings, lists, or tuples, into a single
sequence.
• When applied to tuples, the concatenation operator joins the
elements of the two (or more) tuples to create a new tuple
containing all the elements from both tuples
Updating Tuples Using Concatenation
Operator
Updating Tuples Using Slicing

• Slicing in Python is used to extract a portion of a sequence


(such as a list, tuple, or string) by specifying a range of indices.
The syntax for slicing is as follows:
• start is the index at which the slice begins (inclusive).
• stop is the index at which the slice ends (exclusive).
• step is the interval between elements in the slice (optional).
Updating Tuples Using Slicing
Python Fundamentals
Converting a String to a List
• Both strings and lists in Python are sequence types, they are
interconvertible. Thus, we can cast a string to a list, modify the
list using methods like insert(), append(), or remove() and then
convert the list back to a string to obtain a modified version
Python - Sets

• A set is an unordered collection of unique elements. Unlike


lists or tuples, sets do not allow duplicate values i.e. each
element in a set must be unique.
• Sets are mutable, meaning you can add or remove items after a
set has been created.
• Sets are defined using curly braces {} or the built-
in set() function.
Python - Sets

• They are particularly useful for membership testing, removing


duplicates from a sequence, and performing common
mathematical set operations like union, intersection, and
difference
Creating a Set in Python

• Creating a set in Python refers to defining and initializing a


collection of unique elements.
• This includes specifying the elements that will be part of the
set, ensuring that each element is unique within the set
Using the set() Function

• Alternatively, you can create a set using the set() function by


passing an iterable (like a list or a tuple) containing the
elements you want to include in the set
Python - Access Set Items

• The primary way to access set items is by traversing the set


using a loop, such as a for loop. By iterating over the set, you
can access each element one by one and perform operations
on them as needed.
• In Python, sets are unordered collections of unique elements,
and unlike sequences (such as lists or tuples), sets do not have
a positional index for their elements. This means that you
cannot access individual elements of a set directly by
specifying an index.
Access Set Items Using For Loop

• A for loop in Python is a control flow statement used for


iterating over a sequence and executing a block of code for
each element in the sequence. The loop continues until all
elements have been processed.
• We can access set items using a for loop by iterating over
each element in the set sequentially. Since sets are unordered
collections of unique elements, a for loop provides a
convenient way to traverse the set and access each element
one by one.
Access Set Items Using For Loop
Checking if Set Item Exists

• You can check whether a certain item is available in the set


using the Python's membership operators, in and not in.
• The in operator returns True if the specified element is
found within the collection, and False otherwise.
Conversely, the not in operator returns True if the
element is not present in the collection, and False if it is.
Checking if Set Item Exists
Add Set Items

• Adding set items implies including new elements into an


existing set. In Python, sets are mutable, which means you
can modify them after they have been created.
• While the elements within a set must be immutable (such
as integers, strings, or tuples), the set itself can be
modified.
• You can add items to a set using various methods, such as
add(), update(), or set operations like union (|) and set
comprehension
Add Set Items Using the add()
Method

• The add() method in Python is used to add a single element


to the set. It modifies the set by inserting the specified
element if it is not already present.
• If the element is already in the set, the add() method has no
change in the set.
• Following is the syntax to add an element to a set:
Add Set Items Using the add()
Method
Add Set Items Using the update()
Method

• The update() method of set class is used to add multiple


elements to the set. It modifies the set by adding elements
from an iterable (such as another set, list, tuple, or string)
to the current set.
• The elements in the iterable are inserted into the set if
they are not already present.
• Following is the syntax to update an element to a set
Add Set Items Using the update()
Method
Add Set Items Using Union
Operator

• The union operator (|) is used to perform a union


operation between two sets. The union of two sets
contains all the distinct elements present in either of the
sets, without any duplicates.
Remove Set Items

• Removing set items implies deleting elements from a set. In


Python, sets are mutable, unordered collections of unique
elements, and there are several methods available to remove
items from a set based on different criteria.
• We can remove set items in Python using various methods
such as remove(), discard(), pop(), clear(), and set
comprehension. Each method provide different ways to
eliminate elements from a set based on specific criteria or
conditions.
Remove Set Item Using remove()
Method

• The remove() method in Python is used to remove the first


occurrence of a specified item from a set.
• We can remove set items using the remove() method by
specifying the element we want to remove from the set. If
the element is present in the set, it will be removed.
• However, if the element is not found, the remove() method
will raise a KeyError exception.
Remove Set Item Using remove()
Method
Loop Through Set Items

• Looping through set items in Python refers to iterating over


each element in a set. We can later perform required
operations on each item. These operation includes list
printing elements, conditional operations, filtering elements
etc.
• Unlike lists and tuples, sets are unordered collections, so the
elements will be accessed in an arbitrary order. You can use
a for loop to iterate through the items in a set.
Loop Through Set Items with For
Loop

• A for loop in Python is used to iterate over a sequence (like a


list, tuple, dictionary, string, or range) or any other iterable
object. It allows you to execute a block of code repeatedly
for each item in the sequence.
• In a for loop, you can access each item in a sequence using a
variable, allowing you to perform operations or logic based
on that item's value. We can loop through set items using for
loop by iterating over each item in the set.
Loop Through Set Items with For
Loop
Python - Dictionaries

• Dictionary is a built-in data type that stores data in key-value


pairs. It is an unordered, mutable, and indexed collection.
• Each key in a dictionary is unique and maps to a value.
Dictionaries are often used to store data that is related, such
as information associated with a specific entity or object,
where you can quickly retrieve a value based on its key.
Python - Dictionaries

• Python's dictionary is an example of a mapping type. A


mapping object 'maps' the value of one object to another. To
establish mapping between a key and a value, the colon (:)
symbol is put between the two.
capitals = {"Maharashtra":"Mumbai",
"Gujarat":"Gandhinagar", "Telangana":"Hyderabad",
"Karnataka":"Bengaluru"}
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
marks = {"Savita":67, "Imtiaz":88, "Laxman":91,
"David":49}
Key Features of Dictionaries
Creating a Dictionary

• You can create a dictionary in Python by placing a comma-


separated sequence of key-value pairs within curly braces {},
with a colon : separating each key and its associated value.
Alternatively, you can use the dict() function.
Access Dictionary Items

• Accessing dictionary items in Python involves retrieving the


values associated with specific keys within a dictionary data
structure.
• Dictionaries are composed of key-value pairs, where each key
is unique and maps to a corresponding value. Accessing
dictionary items allows you to retrieve these values by
providing the respective keys.
• There are various ways to access dictionary items in Python:
Access Dictionary Items

• There are various ways to access dictionary items in Python:


• Using square brackets []
• The get() method
• Iterating through the dictionary using loops
• Or specific methods like keys(), values(), and items()
Access Dictionary Items

• The square brackets [] are used for creating lists, accessing


elements from a list or other iterable objects (like strings,
tuples, or dictionaries), and for list comprehension.
• We can access dictionary items using square brackets by
providing the key inside the brackets. This retrieves the value
associated with the specified key.
Access Dictionary Items

• In the following example, we are defining a dictionary named


"capitals" where each key represents a state and its
corresponding value represents the capital city.
• Then, we access and retrieve the capital cities of Gujarat and
Karnataka using their respective keys 'Gujarat' and 'Karnataka'
from the dictionary
Access Dictionary Items Using get()
Method

• The get() method in Python's dict class is used to retrieve


the value associated with a specified key. If the key is not
found in the dictionary, it returns a default value (usually
None) instead of raising a KeyError.
• We can access dictionary items using the get() method by
specifying the key as an argument. If the key exists in the
dictionary, the method returns the associated value;
otherwise, it returns a default value, which is often None
unless specified otherwise.
Access Dictionary Items Using get()
Method

• Syntax:
• In the example below, we are defining a dictionary named
"capitals" where each key-value pair maps a state to its
capital city. Then, we use the get() method to retrieve the
capital cities of "Gujarat" and "Karnataka"
Change Dictionary Items

• Changing dictionary items in Python refers to modifying the


values associated with specific keys within a dictionary. This
can involve updating the value of an existing key, adding a
new key-value pair, or removing a key-value pair from the
dictionary.
• Dictionaries are mutable, meaning their contents can be
modified after they are created.
Modifying Dictionary Values

• Modifying values in a Python dictionary refers to changing the


value associated with an existing key. To achieve this, you can
directly assign a new value to that key.
• Example
• In the following example, we are defining a dictionary named
"person" with keys 'name', 'age', and 'city' and their
corresponding values. Then, we modify the value associated with
the key 'age' to 26
Modifying Dictionary Values
Add Dictionary Items

• Adding dictionary items in Python refers to inserting


new key-value pairs into an existing dictionary.
Dictionaries are mutable data structures that store
collections of key-value pairs, where each key is
associated with a corresponding value.
• Adding items to a dictionary allows you to dynamically
update and expand its contents as needed during
program execution.
Add Dictionary Items

• We can add dictionary items in Python using various ways such as:
• Using square brackets
• Using the update() method
• Using a comprehension
• Using unpacking
• Using the Union Operator
• Using the |= Operator
• Using setdefault() method
• Using collections.defaultdict() method
Add Dictionary Item Using the
update() Method

• The update() method in Python dictionaries is used to


merge the contents of another dictionary or an iterable of
key-value pairs into the current dictionary. It adds or
updates key-value pairs, ensuring that existing keys are
updated with new values and new keys are added to the
dictionary.
• You can add multiple items to a dictionary using the
update() method by passing another dictionary or an iterable
of key-value pairs.
Add Dictionary Item Using the
update() Method

• In the following example, we use the update() method to


add multiple new key-value pairs 'Kavya': 58 and 'Mohan':
98 to the dictionary 'marks‘.
Remove Dictionary Items

• Removing dictionary items in Python refers to deleting key-value


pairs from an existing dictionary. Dictionaries are mutable data
structures that hold pairs of keys and their associated values. Each
key acts as a unique identifier, mapping to a specific value within
the dictionary.
• Removing items from a dictionary allows you to eliminate
unnecessary or unwanted data from the dictionary, thereby
reducing its size and modifying its content
Remove Dictionary Items

• We can remove dictionary items in Python using various ways


such as :
• using the del keyword
• using the pop() method
• using the popitem() method
• using the clear() method
• using dictionary comprehension
Remove Dictionary Items Using del
Keyword

• The del keyword in Python is used to delete objects. In the


context of dictionaries, it is used to remove an item or a slice
of items from the dictionary, based on the specified key(s).
• We can remove dictionary items using the del keyword by
specifying the key of the item we want to remove. This will
delete the key-value pair associated with the specified key
from the dictionary
Remove Dictionary Items Using del
Keyword

• In the following example, we are creating a dictionary named


numbers with integer keys and their corresponding string
values. Then, delete the item with the key '20' using the del
keyword.
Loop Dictionaries

• Looping through dictionaries in Python refers to iterating over


key-value pairs within the dictionary and performing operations
on each pair. This allows you to access both keys and their
corresponding values.
Loop Dictionaries

• There are several ways/methods for looping through


dictionaries:
• Using a for Loop
• Using dict.items() method
• Using dict.keys() method
• Using dict.values() method
Loop Through Dictionary Using a
For Loop

• A for loop in Python is a control flow statement that iterates


over a sequence of elements. It repeatedly executes a block of
code for each item in the sequence. The sequence can be a
range of numbers, a list, a tuple, a string, or any iterable object.
• We can loop through dictionaries using a for loop in Python by
iterating over the keys or key-value pairs within the dictionary.
There are two common approaches
Loop Through Dictionary Using a
For Loop

Example: Iterating over Keys


• In this approach, the loop iterates over the keys of the
dictionary. Inside the loop, you can access the value
corresponding to each key using dictionary indexing
Loop Through Dictionary Using a
For Loop

Example: Iterating over Key-Value Pairs


• In this approach, the loop iterates over the key-value pairs
using the items() method of the dictionary. Each iteration
provides both the key and its corresponding value
Arrays in Python

• Python does not have built-in support for arrays.


However, Python has several data types like lists and
tuples (especially lists) that are often used as arrays but,
items stored in these types of sequences need not be of
the same type.
• In addition, we can create and manipulate arrays the using
the array module. Before proceeding further, let's
understand arrays in general
What are arrays?

• An array is a container which can hold a fix number of items


and these items should be of the same type. Each item stored
in an array is called an element and they can be of any type
including integers, floats, strings, etc.
• These elements are stored at contiguous memory location.
Each location of an element in an array has a
numerical index starting from 0. These indices are used to
identify and access the elements.
Array Representation
• Arrays are represented as a collection of multiple containers
where each container stores one element. These containers are
indexed from '0' to 'n-1', where n is the size of that particular
array.
• Arrays can be declared in various ways in different languages.
Array Representation

• As per the above illustration, following are the important points


to be considered:
• Index starts with 0.
• Array length is 10 which means it can store 10 elements.
• Each element can be accessed via its index. For example, we can fetch
an element at index 6 as 9.
Creating Array in Python

• o create an array in Python, import the array module and use


its array() function. We can create an array of three basic
types namely integer, float and Unicode characters using this
function.
• The array() function accepts typecode and initializer as a
parameter value and returns an object of array class.
Creating Array in Python
Syntax
• The syntax for creating an array in Python is

•typecode − The typecode character used to speccify the type of


elements in the array.
•initializer − It is an optional value from which array is initialized.
It must be a list, a bytes-like object, or iterable elements of the
appropriate type.
Creating Array in Python

• Example
The following example shows how to create an array in Python
using the array module:
Basic Operations on Python Arrays

• Traverse − Print all the array elements one by one.


• Insertion − Adds an element at the given index.
• Deletion − Deletes an element at the given index.
• Search − Searches an element using the given index
or by the value.
• Update − Updates an element at the given index.
Accessing Array Element

• We can access each element of an array using the index of


the element.
Example
• The below code shows how to access elements of an
array.
Insert element in array
• In insertion operation, we insert one or more data elements
into an array. Based on the requirement, a new element can be
added at the beginning, end, or any given index of array.
• Example
• Here, we add a data element at the middle of the array using
the python in-built insert() method.
Deletion Operation

• Deletion refers to removing an existing element from the array


and re-organizing all elements of an array.
• Here, we remove a data element at the middle of the array
using the python in-built remove() method.
Search Operation

• You can perform a search operation on an array to find an array


element based on its value or its index.
Example
• Here, we search a data element using the python in-built index()
method
Update Operation

Update operation refers to updating an existing element from the


array at a given index. Here, we simply reassign a new value to the
desired index we want to update.
Example
• In this example, we are updating the value of array element at
index 2.
END

You might also like