Python Data Structure
Python Data Structure
MILIND ANKLESHWAR
What is Data Structure?
The data structure name indicates itself that organizing the data in memory.
There are many ways of organizing the data in the memory as we have already seen one of the data
structures, i.e., array.
Array is a collection of memory elements in which data is stored sequentially, i.e., one after another. In
other words, we can say that array stores the elements in a continuous manner.
This organization of data is done with the help of an array of data structures.
There are also other ways to organize the data in memory. Let's see the different types of data structures.
The data structure is not any programming language like C, C++, java, etc. It is a set of algorithms that we
can use in any programming language to structure the data in the memory.
To structure the data in memory, 'n' number of algorithms were proposed, and all these algorithms are
known as Abstract data types. These abstract data types are the set of rules.
Types of Data Structures
The major or the common operations that can be performed on the data structures are:
Searching: We can search for any element in a data structure.
Sorting: We can sort the elements of a data structure either in an ascending or descending order.
Insertion: We can also insert the new element in a data structure.
Updation: We can also update the element, i.e., we can replace the element with another element.
Deletion: We can also perform the delete operation to remove the element from the data structure.
Advantages of Data structures
Changeable
The list is changeable, meaning that we can change, add, and remove items in a list after it has been
created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
List Items - Data Types
From Python's perspective, lists are defined as objects with the data type 'list':
<class 'list'>
What is the data type of a list?
mylist = ["apple", "banana", "cherry"]
print(type(mylist))
The list() Constructor
List items are indexed and you can access them by referring to the index number:
Example
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.
Example
Return the third, fourth, and fifth item:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
By leaving out the start value, the range will start at the first item:
This example returns the items from the beginning to, but NOT included, "kiwi":
Example
Check if "apple" is present in the list:
extend() Add the elements of a list (or any iterable), to the end of
the current list
index() Returns the index of the first element with the specified
value
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.
Allow Duplicates
Since tuple are indexed, tuples can have items with the same value:
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Tuple items can be of any data type:
Example
String, int and boolean data types:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
A tuple can contain different data types:
Example
A tuple with strings, integers and boolean values:
tuple1 = ("abc", 34, True, 40, "male")
type()
From Python's perspective, tuples are defined as objects with the data type 'tuple':
<class 'tuple'>
Example
What is the data type of a tuple?
Example
Convert the tuple into a list, remove "apple", and convert it back into a tuple:
Example
Join two tuples:
Method Description
count() Returns the number of times a specified value occurs in a tuple
index() Searches the tuple for a specified value and returns the position of
where it was found
Python Sets
Sets are used to store multiple items in a single variable.
Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List,
Tuple, and Dictionary, all with different qualities and usage.
A set is a collection which is both unordered and unindexed.
Sets are written with curly brackets.
Example
Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)
Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.
Unordered
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and cannot be referred to by
index or key.
Unchangeable
Sets are unchangeable, meaning that we cannot change the items after the set has been
created.
Once a set is created, you cannot change its items, but you can add new items.
Duplicates Not Allowed
Sets cannot have two items with the same value.
Example
Duplicate values will be ignored:
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)
Set items can be of any data type:
Example
String, int and boolean data types:
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
A set can contain different data types:
Example
A set with strings, integers and boolean values:
set1 = {"abc", 34, True, 40, "male"}
Type()
From Python's perspective, sets are defined as objects with the data type 'set':
<class 'set'>
What is the data type of a set?
myset = {"apple", "banana", "cherry"}
print(type(myset))
The set() Constructor
Once a set is created, you cannot change its items, but you can add new items.
Add Items
Once a set is created, you cannot change its items, but you can add new items.
To add one item to a set use the add() method.
Example
Add an item to a set, using the add() method:
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
Add Sets
To add items from another set into the current set, use the update() method.
Example
Add elements from tropical and thisset into newset:
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)
Add Any Iterable
The object in the update() method does not have be a set, it can be any iterable object (tuples,
lists, dictionaries et,).
Example
Add elements of a list to at set:
thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]
thisset.update(mylist)
print(thisset)
Remove Item
Note: If the item to remove does not exist, remove() will raise an error.
Discard() method
Remove "banana" by using the discard() method:
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
Note: If the item to remove does not exist, discard() will NOT raise an error.
Join Two Sets
There are several ways to join two or more sets in Python.
You can use the union() method that returns a new set containing all items from both sets, or
the update() method that inserts all the items from one set into another:
Example
The union() method returns a new set with all items from both sets:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
The update() method inserts the items in set2 into set1:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
Both union() and update() will exclude any duplicate items.
Keep ONLY the Duplicates
The intersection_update() method will keep only the items that are present in both sets.
Example
Keep the items that exist in both set x, and set y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.intersection_update(y)
print(x)
Python - Set Methods
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two or more sets
difference_update() Removes the items in this set that are also included in another,
specified set
intersection_update() Removes the items in this set that are not present in other, specified
set(s)
symmetric_difference_update() inserts the symmetric differences from this set and another
Dictionary items are unordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
Example
Print the "brand" value of the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
Unordered
When we say that dictionaries are unordered, it means that the items does not have a defined
order, you cannot refer to an item by using an index.
Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the
dictionary has been created.
Duplicates Not Allowed
Dictionaries cannot have two items with the same key:
Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets:
Example
Get the value of the "model" key:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
There is also a method called get() that will give you the same result:
Example
Get the value of the "model" key:
x = thisdict.get("model")
Get Keys
The keys() method will return a list of all the keys in the dictionary.
Example
Get a list of the keys:
x = thisdict.keys()
The list of the keys is a view of the dictionary, meaning that any changes done to the dictionary will be reflected in the keys list.
Example
Add a new item to the original dictionary, and see that the keys list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
print(x) #before the change
car["color"] = "white"
print(x) #after the change
Get Values
The values() method will return a list of all the values in the dictionary.
Example
Get a list of the values:
x = thisdict.values()
The list of the values is a view of the dictionary, meaning that any changes done to the dictionary will be reflected in the values list.
Example
Add a new item to the original dictionary, and see that the keys list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
Get Items
The items() method will return each item in a dictionary, as tuples in a list.
Example
Get a list of the key:value pairs
x = thisdict.items()
Check if Key Exists
You can change the value of a specific item by referring to its key name:
Example
Change the "year" to 2018:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
Update Dictionary
The update() method will update the dictionary with the items from the given argument.
The argument must be a dictionary, or an iterable object with key:value pairs.
Example
Update the "year" of the car by using the update() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Update Dictionary
The update() method will update the dictionary with the items from a given argument. If the item does not exist,
the item will be added.
The argument must be a dictionary, or an iterable object with key:value pairs.
Example
Add a color item to the dictionary by using the update() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})
Removing Items
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes
made in dict1 will automatically also be made in dict2.
There are ways to make a copy, one way is to use the built-in Dictionary method copy().
Example
Make a copy of a dictionary with the copy() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict
Another way to make a copy is to use the built-in function dict().
Example
Make a copy of a dictionary with the dict() function:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
Dictionary Methods
Method Description
clear() Removes all the elements from the
dictionary
There are four collection data types in the Python programming language:
List is a collection which is ordered and changeable. Allows duplicate members.
Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
Set is a collection which is unordered and unindexed. No duplicate members.
Dictionary is a collection which is unordered and changeable. No duplicate members.
When choosing a collection type, it is useful to understand the properties of that type. Choosing
the right type for a particular data set could mean retention of meaning, and, it could mean an
increase in efficiency or security.
Address: Narhe, Pune, 411041
Email: milind@masstechnologies.co.in/milind.ankleshwar@gmail.com
Web: http://www.masstechnologies.co.in