Data Structures
Data Structures
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
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.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]
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]
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)
• 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'
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
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
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