unit-2 - More data types- List, tuples, set, dict
unit-2 - More data types- List, tuples, set, dict
28
Everything is an object
Everything means
>>> x = 7
everything, >>> x
including functions 7
and classes (more >>> x = 'hello'
on this later!) >>> x
'hello'
Data type is a
>>>
property of the
object and not of
the variable
Numbers: Integers
Integer – the
equivalent of a C long >>> 132224
Long Integer – an 132224
unbounded integer >>> 132323 **
2
value. 17509376329L
>>>
Numbers: Floating Point
+ is overloaded to do
concatenation >>> x = 'hello'
>>> x = x + ' there'
>>> x
'hello there'
String Literals
Can use single or double quotes, and
three double quotes for a multi-line
string
List
operations as Strings
List Functions
list.append(x)
Add item at the end of the list.
list.insert(i,x)
Insert item at a given position.
Similar to a[i:i]=[x]
list.remove(x)
Removes first item from the list with value x
list.pop(i)
Remove item at position I and return it. If no index I is given then
remove the first item in the list.
list.index(x)
Return the index in the list of the first item with value x.
list.count(x)
Return the number of time x appears in the list
list.sort()
Sorts items in the list in ascending order
list.reverse()
Reverses items in the list
Lists: Modifying Content
mathematical
expression (2)
Sets
A set is another python data structure that is an unordered
collection with no duplicates.
>>> setA=set(["a","b","c","d"])
>>> setB=set(["c","d","e","f"])
>>> "a" in setA
True
>>> "a" in setB
False
Sets
>>> setA - setB
{'a', 'b'}
>>> setA | setB
{'a', 'c', 'b', 'e', 'd', 'f'}
>>> setA & setB
{'c', 'd'}
>>> setA ^ setB
{'a', 'b', 'e', 'f'}
>>>
Dictionaries
>>> d
{1: 'hello', 2: 'there', 10: 'world'}
>>> del(d[2])
>>> d
{1: 'hello', 10: 'world'}
Iterating over a dictionary