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

Data Structures

The document provides an overview of data structures in Python, focusing on lists, tuples, sets, and dictionaries. It explains the characteristics, methods, and operations associated with each data structure, including how to create, modify, and access elements. Additionally, it discusses the differences between mutable and immutable types, as well as techniques for cloning lists.

Uploaded by

Job Up
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Data Structures

The document provides an overview of data structures in Python, focusing on lists, tuples, sets, and dictionaries. It explains the characteristics, methods, and operations associated with each data structure, including how to create, modify, and access elements. Additionally, it discusses the differences between mutable and immutable types, as well as techniques for cloning lists.

Uploaded by

Job Up
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

DATA STRUCTURES IN PYTHON

Python Collections/Data Structures


• 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, unchangeable*, and unindexed. No
duplicate members.
• Dictionary is a collection which is ordered** and changeable. No duplicate
members.
List
• Compound data type
• A list contains items separated by commas and enclosed within square brackets
• Lists are similar to arrays in C.
• Difference - a list can be of different data type
• Accessed using the slice operator ([ ] and [:]) with indexes
• (+) sign is the list concatenation operator, (*) is the repetition operator
Lists
• Lists are used to store multiple items in a single variable.
• Ordered
• Changeable
• Allow Duplicates
Creating a List
• list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
• list1 = ["abc", 34, True, 40, "male"]
• thislist = list(("apple", "banana", "cherry"))
• List=[ ] # empty list creation
Accessing List Elements

list=['vit', 4,5.6,False]
print(list[1])
print(list[1:4])
print(list[-1:-5:-1])
print(list[-1::-1])
print(list[:4])
Change List Items
• thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant“
• thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
• Change the second value by replacing it with two new values
• thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
Change the second and third value by replacing it with one value:
thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
Add List Items
• thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
• thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
• thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
Remove List Items

• thislist = ["apple", "banana", "cherry"] • thislist = ["apple", "banana", "cherry"]


thislist.remove("banana") del thislist[0]
• Pop() remove from the specified index
• thislist = ["apple", "banana", "cherry"]
• thislist.pop(1) del thislist
• Pop() also remove the last item • thislist = ["apple", "banana", "cherry"]
• thislist = ["apple", "banana", "cherry"] thislist.clear() # clear the list, make an
thislist.pop() empty
Loop Through a List
• thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
• thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])
• thislist = ["apple", "banana", "cherry"]
[print(x) for x in thislist]
List Comprehension
• List comprehension offers a shorter syntax when you want to create a new list
based on the values of an existing list.
• fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist)
List Comprehension
• More time-efficient and space-efficient than loops
• Require fewer lines of code
• newList = [ expression(element) for element in oldList if condition]
Other example
• fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []

for x in fruits:
if "a" in x:
newlist.append(x)

print(newlist)
LIST MODULE
• Built-in functions and methods in lists

Function Description
cmp(list1, list2) Compares elements of both lists
len(list) Gives total length of list
max(list) Returns item from the list with maximum value
min(list) Returns item from the list with minimum value
list(seq) Converts a tuple to list
list.append(obj) Appends object obj to list
list.count(obj) Returns count of how many times obj occurs in list
list.insert(index, obj) Inserts object obj into list at offset index
obj = list.pop() Removes the item at position -1 from list and assigns it to obj
list.remove(obj) Removes object obj from list
list.reverse() Reverses the order of items in list
sorted(list) Sorts items in list
14
Sort List
• thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
• thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True)
print(thislist)
Reverse Order

• thislist = ["banana", "Orange", "Kiwi", "cherry"]

thislist.reverse()

print(thislist)
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
Add the elements of a list (or any iterable), to the end of the
extend()
current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Cloning or Copying a list
• Using the slicing technique
• Using the extend() method
• List copy using = (assignment operator)
• Using the method of Shallow Copy
• Using list comprehension
• Using the append() method
• Using the copy() method
• Using the map method

18
Example
# Python program to copy or clone a list
# Using the Slice Operator
def Cloning(li1):
li_copy = li1[:]
return li_copy

# Driver Code
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1)
print("Original List:", li1)
print("After Cloning:", li2)

19
Example
# Python code to clone or copy a list
# Using the in-built function extend()
def Cloning(li1):
li_copy = []
li_copy.extend(li1)
return li_copy

# Driver Code
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1)
print("Original List:", li1)
print("After Cloning:", li2)

20
Example
# Python code to clone or copy a list
# Using the List copy using =
def Cloning(li1):
li_copy = li1
return li_copy

# Driver Code
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1)
print("Original List:", li1)
print("After Cloning:", li2)
21
Example
# importing copy module
import copy

# initializing list 1
li1 = [1, 2, [3,5], 4]

# using copy for shallow copy


li2 = copy.copy(li1)

print(li2)

22
Example
# Python code to clone or copy a list
# Using list comprehension
def Cloning(li1):
li_copy = [i for i in li1]
return li_copy

# Driver Code
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1)
print("Original List:", li1)
print("After Cloning:", li2)
23
Example
# Python code to clone or copy a list
# Using built-in method copy()
def Cloning(li1):
li_copy =[]
li_copy = li1.copy()
return li_copy

# Driver Code
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1)
print("Original List:", li1)
print("After Cloning:", li2)

24
Example
# importing copy module
import copy

# initializing list 1
li1 = [1, 2, [3,5], 4]

# using deepcopy for deepcopy


li3 = copy.deepcopy(li1)
print(li3)

25
List () Parameters
• It is used to create a list object

• A list object refers to the collection of data that is ordered and changeable

• Syntax:

list (iterable)

• iterable refers to the sequence of collection of data

• If there are no parameters in the list () Python function, then it will return an
empty list

26
Create lists from string, tuple, and lists
text = 'Python'

# convert string to list


text_list = list(text)
print(text_list)

# check type of text_list


print(type(text_list))

27
Example 1: Create lists from string, tuple, and list
# empty list
print(list())
# vowel string
vowel_string = 'aeiou'
print(list(vowel_string))
# vowel tuple
vowel_tuple = ('a', 'e', 'i', 'o', 'u')
print(list(vowel_tuple))
# vowel list
vowel_list = ['a', 'e', 'i', 'o', 'u']
print(list(vowel_list))

28
Create lists from set and dictionary
# vowel set
vowel_set = {'a', 'e', 'i', 'o', 'u'}
print(list(vowel_set))

# vowel dictionary
vowel_dictionary = {'a': 1, 'e': 2, 'i': 3, 'o':4, 'u':5}
print(list(vowel_dictionary))

29
Tuples
• A tuple is another sequence data type that is similar to the list
• A tuple consists of a number of values separated by commas
• Unlike lists, however, tuples are enclosed within parentheses
• Tuples can be thought of as read-only lists

30
Tuples - Example

31
Tuples - Output

32
Difference – Lists and Tuples

33
TUPLES
• Built-in functions and methods in tuples

Function Description
Return True if all elements of the tuple are true (or if the tuple is
all()
empty).
Return True if any element of the tuple is true. If the tuple is
any()
empty, return False.
Return an enumerate object. It contains the index and value of
enumerate()
all the items of tuple as pairs.
len() Return the length (the number of items) in the tuple.
max() Return the largest item in the tuple.
min() Return the smallest item in the tuple
Take elements in the tuple and return a new sorted list (does not
sorted()
sort the tuple itself).
sum() Return the sum of all elements in the tuple.
tuple() Convert an iterable (list, string, set, dictionary) to a tuple.
34
Unpacking a Tuple
• fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
• fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)

35
Dictionary
• Hash table type
• Work like associative arrays or hashes - consist of key-value pairs.
• Key - any Python type, but are usually numbers or strings
• Enclosed by curly braces ({ }) and values can be assigned and accessed using
square braces ([])

36
Example

37
Example -Output

38
PYTHON DICTIONARY METHODS
Function Description

clear() Remove all items form the dictionary.


values() Return a new view of the dictionary's values
keys() Return a new view of the dictionary's keys.
Update the dictionary with the key/value pairs from
update([other])
other, overwriting existing keys.
Return a new dictionary with keys from seq and value
fromkeys(seq[, v])
equal to v (defaults to None).
Return the value of key. If key doesnot exit, return d
get(key[,d])
(defaults to None).
Remove the item with key and return its value or d if key
pop(key[,d]) is not found. If d is not provided and key is not found,
raises KeyError.
Return the length (the number of items) in the
len()
dictionary.
39
cmp() Compares items of two dictionaries.
sorted() Return a new sorted list of keys in the dictionary.
SETS
• An un-ordered collection of unique elements
• Are lists with no index value and no duplicate entries
• Can be used to identify unique words used in a paragraph

set1 = {} #Creation of empty set


Syntax:
set2 = {“John”} #Set with an element

s1 = set("my name is John and John is my name".split())


Example:
s1 = {'is', 'and', 'my', 'name', 'John'}

• Operations like intersection, difference, union, etc can be performed on


sets

40
OPERATIONS ON SETS
Operation Equivalent Operation
len (s) Length of set ‘s’
x in s Membership of ‘x’ in ‘s’
x not in s Membership of ‘x’ not in ‘s’
s.issubset(t) s <= t Check whether ‘s’ is subset ‘t’
s.issuperset(t) s >= t Check whether ‘t’ is superset of ‘s’
s.union(t) s|t Union of sets ‘s’ and ‘t’
s.intersection(t) s&t Intersection of sets ‘s’ and ‘t’
s.difference(t) s -t Returns elements in ‘s’ but not in ‘t’
s.symmetric_difference(t) s ^ t Returns elements in either ‘s’ or ‘t’ but
not both
s.copy(_) A new copy of ‘s’

41
MUTABLE V/S IMMUTABLE DATA TYPES
Mutable Data Type Immutable Data Type

Sequences can be modified Sequences cannot be modified


after creation after creation
Ex: Lists, Sets, Dictionary Ex: Strings, Tuples
Operations like add, delete and Operations like add, delete and
update can be performed update cannot be performed
Example
int_list = [12, 14, 9]
int_tuple = (12, 14, 19)

int_list[0] = 7
#prints [7, 14, 9] Output
print("List: ", int_list) List: [7, 14, 9]
int_tuple[0] = 7
int_tuple[0] = 7 TypeError: 'tuple' object does
#Prints TypeError: 'tuple' object does not support not support item assignment
#item assignment
print("Tuple: ", int_tuple)
42
What is a list of lists?
• lists are used to store more than one item in a single variable
• It can be used to store integer, float, string and more.
• creating a list within a list – Nested List
• l=[['a','b'],['c','d'],['e','f'],"VIT"]
44

You might also like