Data types are classes that are used to define the operations possible on them and their storage methods
Some standard data types are :
Number data types store numeric values
Number objects can be created by assigning values
Numerical types supported by Python :
long, a datatype of Python 2.7, got merged with int in python 3, so numbers followed byL
orl
are considered invalid in python 3
Integers can be of any length, although limited by the available memory
A floating point number is accurate up to 15 decimal places
A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj
, where x
and y
are real numbers and j
is the imaginary unit
>>> a = 1234567890123456789
>>> a
1234567890123456789
>>> b =0.1234567890123456789012
>>> b
0.12345678901234568
>>> c =1+2j
>>> c
(1+2j)
As shown, float
variable b gets truncated
Numbers can also be scientific numbers with an "e" to indicate the power of 10
type()
function can be used to know which class a variable or a value belongs to and isinstance()
function can be used to check if an object belongs to a particular class
>>> type(-131)
<class 'int'>
>>> type(-0x231)
<class 'int'>
>>> type(0xabcd)
<class 'int'>
>>> type(14e+244)
<class 'float'>
>>> type(242.0)
<class 'float'>
>>> type(-.1215124)
<class 'float'>
>>> type(.121e242)
<class 'float'>
>>> type(14e-244)
<class 'float'>
>>> type(0j)
<class 'complex'>
>>> type(1.02+412j)
<class 'complex'>
String is sequence of Unicode characters
Single quotes '
or double quotes "
are used to represent strings
Multi-line strings can be denoted using triple quotes, '''
or """
plus +
sign is the concatenation operator and the asterisk *
is the repetition operator
>>> s = "a string"
>>> s
'a string'
>>> s + " concatenation"
'a string concatenation'
>>> s = '''a
... multiline
... string'''
>>> s
'a\n multiline\n string'
>>> s * 3
'a\n multiline\n stringa\n multiline\n stringa\n multiline\n string'
Slice operator ([ ]
and [:]
) can be used with strings with indexes starting at 0
>>> str ='test string'
>>> str[0]
't'
>>> str[2:7]
'st st'
>>> str[7:]
'ring'
Strings are iterable
>>> s = "string"
>>> for x in s:
... print(x)
...
s
t
r
i
n
g
Strings are immutable, i.e., their values cannot be changed, but a variable can be assigned to another string (which can be substring of current string)
>>> s = "string"
>>> s[2]
'r'
>>> s[2] = 'x'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> s = s[0:2] + 'x' + s[3:]
>>> s
'stxing'
List is an ordered collection of objects, where each object can be of different data type
A list contains items separated by commas and enclosed within square brackets [ ]
Declaration :
>>> a =[1,2.2,'python']
Lists are mutable, meaning, value of elements of a list can be altered
>>> a =[1,2,3]
>>> a[2]=4
>>> a
[1,2,4]
The items of a list can be accessed by using slice operator ([ ]
and [:]
) with index starting at 0
Plus +
sign is concatenation operator, and asterisk *
is repetition operator
>>> samplelist = ['Josh', 13, 49.65274, 'water can flow', ['element of list inside list', 76]]
>>> type(samplelist)
<class 'list'>
>>> type(samplelist[2])
<class 'float'>
>>> type(samplelist[4])
<class 'list'>
>>> # length of list
>>> len(samplelist)
5
>>> # usage of slice operator
>>> samplelist[4]
['element of list inside list', 76]
>>> samplelist[4][0]
'element of list inside list'
>>> samplelist[2:5]
[49.65274, 'water can flow', ['element of list inside list', 76]]
>>> anotherlist = samplelist[2:]
>>> anotherlist
[49.65274, 'water can flow', ['element of list inside list', 76]]
>>> # changing value of list element
>>> anotherlist[2] = 'air can flow'
>>> anotherlist
[49.65274, 'water can flow', 'air can flow']
A tuple is an immutable ordered sequence of items, which consists of a number of values separated by commas and enclosed within parentheses ( )
lists vs tuples : Lists are enclosed in brackets [ ]
and their elements and size can be changed, while tuples are enclosed in parentheses ( )
and cannot be modified
>>> t =(5,'program',1+3j)
Slice operator ([ ]
and [:]
) can be used to extract an item, but not to assign new value
>>> sampletuple = ('Josh', 13, 49.65274, 'water can flow', ['one', 2])
>>> sampletuple
('Josh', 13, 49.4883, 'water can flow', ['one', 2])
>>> type(sampletuple)
<class 'tuple'>
>>> # usage of slice operator
>>> sampletuple[1]
13
>>> sampletuple[1:3]
(13, 49.4883)
>>> sampletuple[1:]
(13, 49.4883, 'water can flow', ['one', 2])
>>> # values of tuple elements cannot be changed
>>> sampletuple[2] = '12.23'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> sampletuple[4][2] = 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>> # elements of mutable data-type like a list inside a tuple can be manipulated
>>> sampletuple[4][1] = 1
>>> sampletuple
('Josh', 13, 49.4883, 'water can flow', ['one', 1])
>>> sampletuple[4].append(3)
>>> sampletuple
('Josh', 13, 49.4883, 'water can flow', ['one', 1, 3])
Dictionary is an unordered collection of key-value pairs
Dictionaries are defined within curly braces { }
with each item being a pair in the form key:value
Key and value can be of any type supported by Python
>>> d ={1:'value','key':2}
>>> type(d)
<class'dict'>
Key can be used to retrieve corresponding value but not the other way around
Values can be assigned and accessed using square braces [ ]
#!/usr/bin/python
dict ={}
dict['one']="This is one"
dict[2]="This is two"
# Retrieve value in dict for specific key
print(dict['one'])
print(dict[2])
tinydict = {'name':'john','code':6734,'dept':'sales'}
# Prints complete dictionary
print(tinydict)
# Returns list of keys in dict
print(tinydict.keys())
# Returns list of all values in dict
print(tinydict.values())
Output
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
Set is an unordered collection of unique items
Set is defined by values separated by comma inside curly braces { }
Sets eliminate duplicates
>>> a ={1,2,2,3,3,3}
>>> a
{1,2,3}
Slice operator ([ ]
and [:]
) does not work on sets, as they are unordered
>>> a ={1,2,3}
>>> a[1]
Traceback(most recent call last):
File"<string>", line 301,in runcode
File"<interactive input>", line 1,in<module>
TypeError:'set'object does not support indexing
Operations like union, intersection can be applied on two sets
Union of two sets returns a set containing elements of both sets
a = {1,2,2,3,3,3}
b = {2,3,4,5}
print("a :", a)
print("b :", b)
print("a.union(b) : ", a.union(b))
print("b.union(a) : ", b.union(a))
Output
a : {1, 2, 3}
b : {2, 3, 4, 5}
a.union(b) : {1, 2, 3, 4, 5}
b.union(a) : {1, 2, 3, 4, 5}
Union of two sets returns a set containing common elements between the sets, if any
a ={1,2,2,3,3,3}
b = {3,4,5,6}
c = {6,7}
print("a :", a)
print("b :", b)
print("a.intersection(b) : ", a.intersection(b))
print("b.intersection(a) : ", b.intersection(a))
print("a.intersection(c) : ", a.intersection(c))
print("a.union(b).intersection(c) :", a.union(b).intersection(c))
Output
a : {1, 2, 3}
b : {3, 4, 5, 6}
a.intersection(b) : {3}
b.intersection(a) : {3}
a.intersection(c) : set()
a.union(b).intersection(c) : {6}
To convert between types, the type name is used as a function, which returns a new object based on the converted value
Sr.No | Function | Description |
---|---|---|
1 | int(x [,base]) | Converts x to an integer base specifies the base if x is a string |
2 | long(x [,base] ) | Converts x to a long integer base specifies the base if x is a string |
2 | float(x) | Converts x to a floating-point number |
3 | complex(real [,imag]) | Creates a complex number It doesn't accept a second argument if first argument is string |
4 | str(x) | Converts object x to a string representation |
5 | repr(x) | Converts object x to an expression string |
6 | eval(str) | Evaluates a string and returns an object |
7 | tuple(s) | Converts s to a tuple |
8 | list(s) | Converts s to a list |
9 | set(s) | Converts s to a set |
10 | dict(d) | Creates a dictionary d must be a sequence of (key,value) tuples |
11 | frozenset(s) | Converts s to a frozen set |
12 | chr(x) | Converts an integer to a character |
13 | unichr(x) | Converts an integer to a Unicode character |
14 | ord(x) | Converts a single character to its integer value |
15 | hex(x) | Converts an integer to a hexadecimal string |
16 | oct(x) | Converts an integer to an octal string |
Conversion from float to int truncates the value
>>>int(10.6)
10
>>>int(-30.6)
-30
Conversion to and from string must contain compatible values
>>>float('2.5')
2.5
>>> str(25)
'25'
>>>int('1p')
Traceback(most recent call last):
File"<string>", line 301,in runcode
File"<interactive input>", line 1,in<module>
ValueError: invalid literal forint()withbase10:'1p'
>>>set([1,2,3])
{1,2,3}
>>> tuple({5,6,7})
(5,6,7)
>>> list('hello')
['h','e','l','l','o']
To convert to dictionary, each element must be a pair
>>> dict([[1,2],[3,4]])
{1:2,3:4}
>>> dict([(3,26),(4,44)])
{3:26,4:44}
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
In Type Casting, loss of data may occur as the object is enforced to specific data type