Вы находитесь на странице: 1из 17

Compounded Data Types

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)

• used to return more than one value from a function

def quotient_and_remainder(x, y):


q = x / y
r = x % y
return (q, r)

(quot, rem) = quotient_and_remainder(4,5)


Iterating through Tuples
• t=(1, ‘Ajay’, 2.423)

for item in t: for index, item in enumerate(t):


print(item) print(index, item)

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[1:] ‘a’, 3.2, [1,2]

list[:-1] 2,‘a’, 3.2

list[0]+5 7

i=2
‘a’
list[i-1]
CHANGING ELEMENTS

• lists are mutable!

• assigning to an element at an index changes the value


L = [2, 1, 3]
L[1] = 5

• L is now [2, 5, 3], note this is the same object L


ITERATING OVER A LIST
L=[1,2,3,4,5]

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’]

• Key Value Pair


• Defined in {}
• Values separated by ‘:’
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)

Вам также может понравиться