Dynamic Language
Lecture 2
Introduction to Python
Language.
Mohamed Mead
Python Data Types
Data types are nothing but variables you use to
reserve some space in memory.
Python variables do not need an explicit
declaration to reserve memory space.
The declaration happens automatically when you
assign a value to a variable.
String Data Type
String are identified as a set of characters represented in
the quotation marks.
Python allows for either pairs of single or double quotes.
Strings are immutable sequence data type, i.e each time one
makes any changes to a string, completely new string object is
created.
a_str = 'Hello World'
print(a_str) #output will be whole string. Hello World
print(a_str[0]) #output will be first character. H
print(a_str[0:5]) #output will be first five characters. Hello
String Data Type
The plus (+) sign is the string concatenation operator and
the asterisk (*) is the repetition operator.
str = 'Hello World!'
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string
Numbers data type
Numbers have four types in Python. Int, float, complex,
and long.
int_num = 10 #int value
float_num = 10.2 #float value
complex_num = 3.14j #complex value
long_num = 1234567L #long value
Booleans
A boolean value of either True or False. Logical
operations like and, or, not can be performed on booleans.
x or y # if x is False then y otherwise x
x and y # if x is False then x otherwise y
not x # if x is True then False, otherwise True
Booleans
If boolean values are used in arithmetic operations, their
integer values (1 and 0 for True and False) will be used to
return an integer result:
True + False == 1 # 1 + 0 == 1
True * True == 1 # 1 * 1 == 1
Set Data Types
Sets are unordered collections of unique objects, there are two
types of set:
1. Sets - They are mutable and new elements can be added once sets
are defined
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket) # duplicates will be removed
> {'orange', 'banana', 'pear', 'apple'}
a = set('abracadabra')
print(a) # unique letters in a
> {'a', 'r', 'b', 'c', 'd'}
a.add('z')
print(a)
> {'a', 'c', 'r', 'b', 'z', 'd'}
Set Data Types
2. Frozen Sets - They are immutable and new elements
cannot added after its defined.
b = frozenset('asdfagsa')
print(b)
> frozenset({'f', 'g', 'd', 'a', 's'})
cities = frozenset(["Frankfurt", "Basel","Freiburg"])
print(cities)
> frozenset({'Frankfurt', 'Basel', 'Freiburg'})
Operations on sets - with other sets
# Intersection
{1, 2, 3, 4, 5}.intersection({3, 4, 5, 6}) # {3, 4, 5}
{1, 2, 3, 4, 5} & {3, 4, 5, 6} # {3, 4, 5}
# Union
{1, 2, 3, 4, 5}.union({3, 4, 5, 6}) # {1, 2, 3, 4, 5, 6}
{1, 2, 3, 4, 5} | {3, 4, 5, 6} # {1, 2, 3, 4, 5, 6}
# Difference
{1, 2, 3, 4}.difference({2, 3, 5}) # {1, 4}
{1, 2, 3, 4} - {2, 3, 5} # {1, 4}
Operations on sets - with other sets
# Symmetric difference with
{1, 2, 3, 4}.symmetric_difference({2, 3, 5}) # {1, 4, 5}
{1, 2, 3, 4} ^ {2, 3, 5} # {1, 4, 5}
# Superset check
{1, 2}.issuperset({1, 2, 3}) # False
{1, 2} >= {1, 2, 3} # False
# Subset check
{1, 2}.issubset({1, 2, 3}) # True
{1, 2} <= {1, 2, 3} # True
# Disjoint check
{1, 2}.isdisjoint({3, 4}) # True
{1, 2}.isdisjoint({1, 4}) # False
Operations on sets - with single elements
# Existence check
2 in {1,2,3} # True
4 in {1,2,3} # False
4 not in {1,2,3} # True
# Add and Remove
s = {1,2,3}
s.add(4) # s == {1,2,3,4}
s.discard(3) # s == {1,2,4}
s.discard(5) # s == {1,2,4}
s.remove(2) # s == {1,4}
s.remove(2) # KeyError!
Operations on sets
Method Operator
a.intersection(b) a&b
a.union(b) a|b
a.difference(b) a-b
a.symmetric_difference(b) a^b
a.issubset(b) a <= b
a.issuperset(b) a >= b
Operations on sets
Testing membership
>>> a = {1, 2, 2, 3, 4}
>>> b = {3, 3, 4, 4, 5}
The builtin in keyword searches for occurances
>>> 1 in a
True
>>> 6 in a
False
Length
The builtin len() function returns the number of elements in the set
>>> len(a)
4
>>> len(b)
3
List Data Type
A list contains items separated by commas and enclosed
within square brackets [].lists are almost similar to
arrays in C.
One difference is that all the items belonging to a list
can be of different data type.
List Data Type
list = [123,'abcd',10.2,'d'] #can be an array of any data type or
single data type.
list1 = ['hello','world']
print(list) #will output whole list. [123,'abcd',10.2,'d']
print(list[0:2]) #will output first two element of list.
[123,'abcd']
print(list1 * 2) #will gave list1 two times.
['hello','world','hello','world']
print(list + list1) #will gave concatenation of both the lists.
#[123,'abcd',10.2,'d','hello','world']
Dictionary Data Type
Dictionary consists of key-value pairs. It is enclosed by curly
braces {} and values can be assigned and accessed using square
brackets[].
dic={'name':'red','age':10}
print(dic) #will output all the key-value pairs.
{'name':'red','age':10}
print(dic['name']) #will output only value with 'name' key. 'red'
print(dic.values()) #will output list of values in dic. ['red',10]
print(dic.keys()) #will output list of keys. ['name','age']
Dictionary Data Type
Tuple Data Type
Lists are enclosed in brackets [ ] and their elements and size
can be changed, while tuples are enclosed in parentheses ( )
and cannot be updated. Tuples are immutable.
tuple = (123,'hello')
tuple1 = (33,'world')
print(tuple) #will output whole tuple. (123,'hello')
print(tuple[0]) #will output first value. (123)
print(tuple + tuple1) #will output (123,'hello',33,'world')
tuple[1]='update' #this will give you error.('tuple' object
does not support item assignment)
Tuple Data Type
slicing operator. [start:stop:step].
For example,
my_tuple = ('a', 'b', 'c', 'd')
print(my_tuple[1:]) #Print elements from index 1 to end
print(my_tuple[:2]) #Print elements from start to index 2
print(my_tuple[1:3]) #Print elements from index 1 to index
3
print(my_tuple[::2]) #Print elements from start to end
using step sizes of 2
Python Lists versus Tuples
Lists can hold heterogeneous data types, and so too can tuples:
Python Lists versus Tuples
We can convert a tuple to a list using the list function,
and the tuple function performs the reverse conversion.
Data Type Conversion
Sometimes, you may need to perform conversions
between the built-in types. To convert between types,
you simply use the type name as a function.
There are several built-in functions to perform
conversion from one data type to another. These
functions return a new object representing the
converted value.
Converting between datatypes
For example, '123' is of str type and it can be converted
to integer using int function.
a = '123'
b = int(a)