Compound Data Types - 4
Compound Data Types - 4
TUPLES
• an ordered sequence of elements, can mix element types
• cannot change element values, immutable
• represented with parentheses
t = ()
t = (2,"mit",3)
t[0] 2
t[1:2] (“mit”)
t[1:3] (“mit”,3)
len(t) 3
t[1]=4 gives error, can’t modify object
• conveniently used to swap variable values
(x, y) = (y, x)
Output:
Output: 0 1
1 1 Ajay
Ajay 2 2.423
2.423
Lists
• ordered sequence of information, accessible by index
• a list is denoted by square brackets, []
• a list contains elements
• usually homogeneous (i.e, all integers)
• can contain mixed types (not common)
• list elements can be changed so a list is mutable
list = []
list = [2, ‘a’, 3.2,[1,2]]
len(list) 4
list[0] 2
list[0:3] 2, ‘a’, 3.2
list[0]+5 7
i=2
‘a’
list[i-1]
CHANGING ELEMENTS
total = 0 total = 0
for i in L: for i in range(len(L)):
total += i total += L[i]
print(total) print(total)
OPERATIONS ON LISTS
• Add elements
L=[2,1,3,4,3]
L.append (5)
L is now [2,1,3,4,3,5]
• Remove elements
del(L[1]) [2,3,4,3,5]
L.pop () 5
L.remove(2) [3,4,3,5]
L.remove(3) [4,3,5]
ALIASES
a=[1, ‘Vishal’, 56] Output:
b=a 56
a.pop() [1, ‘Vishal’]
print(a) [1, ‘Vishal’]
print(b)
CLONING A LIST
a=[1, ‘Vishal’, 56] Output:
b=a[:] 56
a.pop() [1, ‘Vishal’]
print(a) [1, ‘Vishal’,56]
print(b)
DICTIONARY
• Student
Name: Vishal
Age: 20
Course: [‘Math’, ‘Physics’]
print(Student[‘Name’])
Output:
Vishal
UPDATES VALUES
Student.update({‘Name’: ‘Vishal’, ‘Age’: 20, ‘Course’:[‘Math’, ‘Physics’]}}
REMOVING VALUES
Student.pop(‘Age’)
Student.keys()
Student.values()
Student.items()
ARRAYS
• Contiguous area of memory broken down into equal sized elements
indexed by contiguous integers.
• Constant time access
import array
arrayName = array(typecode, [Initializers])
• array1 = array. array ('i', [10,20,30,40,50])
• array1.insert(1,60)
• array1.remove(40)