Python Data Structures
DATA
TYPES:
All data values in Python are encapsulated
in relevant object classes. Everything in Python is an object and every object
has an identity, a type, and a value. Like another object-oriented language
such as Java or C++, there are several data types which are built into Python.
To determine a variable's type in Python
you can use the type() function. The value of some objects can be changed.
Objects whose value can be changed are called mutable and objects whose value is unchangeable (once they are
created) are called immutable. Here
are the details of Python data types
Python's built-in (or standard) data types
can be grouped into several classes. They are basically numeric types,
sequences, sets and mappings
Boolean:
the type of the built-in values True and False. Useful in conditional
expressions, and anywhere else you want to represent the truth or falsity of
some condition. Mostly interchangeable with the integers 1 and 0.
Numeric
types:
int: Integers has non-limited length in Python 3.x
long: Long integers of non-limited length;
exists only in Python 2.x
float: Floating-Point numbers(Decimal
Points)
complex: Complex Numbers
Sequences:
str: String; represented as a sequence of
8-bit characters in Python 2.x, but as a sequence of Unicode characters in
Python 3.x
bytes: a sequence of integers in the range
of 0-255; only available in Python 3.x
byte array: like bytes only available in
Python 3.x
list
tuple
Sets:
set: an unordered collection of unique
objects; available as a standard type since Python 2.6
frozen set: like set, available as a
standard type since Python 2.6
Mappings:
dict: Python dictionaries, also called
hash maps or associative arrays, which means that an element of the list is
associated with a definition, rather like a Map in Java
Mutable
vs Immutable Objects
In general, data types in Python can be
distinguished based on whether objects of the type are mutable or immutable.
The content of objects of immutable types cannot be changed after they are
created.
Some immutable types
|
Some mutable types
|
· int, float, long, complex
· str
· bytes
· tuple
· frozen set
·
Boolean
|
1.
array
2.
byte array
3.
list
4.
set
5.
dict
|
Only mutable objects support methods that
change the object in place, such as reassignment of a sequence slice, which
will work for lists, but raise an error for tuples and strings.
Number Data Types:
Numbers are created by numeric literals.
Numeric objects are immutable, which means when an object is created its value
cannot be changed.
Python has three distinct numeric types:
integers, floating point numbers, and complex numbers. Integers represent
negative and positive integers without fractional parts whereas floating point
numbers represents negative and positive numbers with fractional parts. Complex
data types represent real and imaginary part which is of a+bJ or a+bj format.In
addition, Booleans are a subtype of plain integers
Python's built-in core data types are in
some cases also called object types. There are four built-in data types for
numbers:
Integer
Normal integers
e.g. 4321
Octal literals (base 8)
A number prefixed by a 0 (zero) will be
interpreted as an octal number
example:
>>> a = 010
>>> print a
8 Alternatively, an octal number can be
defined with "0o" as a prefix: >>> a = 0o10
>>> print a
8
Hexadecimal literals (base 16)
Hexadecimal literals have to be prefixed
either by "0x" or "0X".
example:
>>> hex_number = 0xA0F
>>> print hex_number
2575
Long integers
these numbers are of unlimited size
e.g.42000000000000000000L
Floating-point numbers
example: 42.11, 3.1415e-10
Complex numbers
Complex numbers are written as <real
part> + <imaginary part>j
2+3j
4j
Quiz
Questions:
1.
a=10
b=a
a=25
print
b
2.
a=255
c=”26”
print
a+c
3.
a=20.3666
c=20.5666
print
a+int(c)
4.
a=2+6j
c=2J
print a+c
print a*c
>>> x = 3 + 4j
>>> y = 2 - 3j
>>> z = x + y
>>> print z
(5+1j)
>>> a=010
>>> a
8
>>> a=0x255
>>> a
597
>>> b=253
>>> c=hex(b)
>>> c
'0xfd'
a = 5
# Output: <class 'int'>
print(type(a))
# Output: <class 'float'>
print(type(5.0))
# Output: (8+3j)
c = 5 + 3j
print(c + 3)
# Output: True
print(isinstance(c, complex))
METHODS:
Description
The method abs() returns absolute value of
x - the (positive) distance between x and zero.
Syntax
Following is the syntax for abs() method −
abs( x )
Parameters
x − This is a numeric expression.
Return Value
This method returns absolute value of x.
Example
The following example shows the usage of
abs() method.
#!/usr/bin/python
print "abs(-45) : ", abs(-45)
print "abs(100.12) : ",
abs(100.12)
print "abs(119L) : ", abs(119L)
When we run above program, it produces
following result −
abs(-45) :
45
abs(100.12) : 100.12
abs(119L) : 119
Number Type Conversion
Python converts numbers internally in an
expression containing mixed types to a common type for evaluation. But
sometimes, you need to coerce a number explicitly from one type to another to
satisfy the requirements of an operator or function parameter.
• Type
int(x) to convert x to a plain integer.
• Type
long(x) to convert x to a long integer.
• Type
float(x) to convert x to a floating-point number.
• Type
complex(x) to convert x to a complex number with real part x and imaginary part
zero.
• Type
complex(x, y) to convert x and y to a complex number with real part x and
imaginary part y. x and y are numeric expression
Methods in Number Data Type:
The method abs() returns absolute value of
x - the (positive) distance between x and zero.
Syntax
Following is the syntax for abs() method:
abs( x )
Ex:
print "abs(-45) : ", abs(-45)
print "abs(100.12) : ",
abs(100.12)
print "abs(119L) : ", abs(119L)
O/p:
abs(-45) :
45
abs(100.12) : 100.12
abs(119L) : 119
2)
The method cmp() returns the sign of the
difference of two numbers : -1 if x < y, 0 if x == y, or 1 if x > y .
Syntax
Following is the syntax for cmp() method:
cmp( x, y )
Parameters
• x
-- This is a numeric expression.
• y
-- This is also a numeric expression
Ex:
print "cmp(80, 100) : ", cmp(80,
100)
print "cmp(180, 100) : ",
cmp(180, 100)
print "cmp(-80, 100) : ",
cmp(-80, 100)
print "cmp(80, -100) : ",
cmp(80, -100)
When we run above program, it produces
following result:
cmp(80, 100) : -1
cmp(180, 100) : 1
cmp(-80, 100) : -1
cmp(80, -100) : 1
3)
Description
The method max() returns the largest of
its arguments: the value closest to positive infinity.
Syntax
Following is the syntax for max() method:
max( x, y, z, .... )
Parameters
• x
-- This is a numeric expression.
• y
-- This is also a numeric expression.
• z
-- This is also a numeric expression.
Return Value
This method returns largest of its
arguments.
Example
The following example shows the usage of
max() method.
#!/usr/bin/python
print "max(80, 100, 1000) : ",
max(80, 100, 1000)
print "max(-20, 100, 400) : ",
max(-20, 100, 400)
print "max(-80, -20, -10) : ",
max(-80, -20, -10)
print "max(0, 100, -400) : ",
max(0, 100, -400)
When we run above program, it produces
following result:
max(80, 100, 1000) : 1000
max(-20, 100, 400) : 400
max(-80, -20, -10) : -10
max(0, 100, -400) : 100
5)
Description
The method min() returns the smallest of
its arguments: the value closest to negative infinity.
Syntax
Following is the syntax for min() method:
min( x, y, z, .... )
Parameters
• x
-- This is a numeric expression.
• y
-- This is also a numeric expression.
• z
-- This is also a numeric expression.
Return Value
This method returns smallest of its
arguments.
Example
The following example shows the usage of
min() method.
#!/usr/bin/python
print "min(80, 100, 1000) : ",
min(80, 100, 1000)
print "min(-20, 100, 400) : ",
min(-20, 100, 400)
print "min(-80, -20, -10) : ",
min(-80, -20, -10)
print "min(0, 100, -400) : ",
min(0, 100, -400)
When we run above program, it produces
following result:
min(80, 100, 1000) : 80
min(-20, 100, 400) : -20
min(-80, -20, -10) : -80
min(0, 100, -400) : -400
6)
Description
The method cos() returns the cosine of x
radians.
Syntax
Following is the syntax for cos() method:
cos(x)
Note: This function is not accessible
directly, so we need to import math module and then we need to call this
function using math static object.
Parameters
• x
-- This must be a numeric value.
Return Value
This method returns a numeric value
between -1 and 1, which represents the cosine of the angle.
Example
The following example shows the usage of
cos() method.
#!/usr/bin/python
import math
print "cos(3) : ", math.cos(3)
print "cos(-3) : ", math.cos(-3)
print "cos(0) : ", math.cos(0)
print "cos(math.pi) : ", math.cos(math.pi)
print "cos(2*math.pi) : ", math.cos(2*math.pi)
When we run above program, it produces
following result:
cos(3) :
-0.9899924966
cos(-3) :
-0.9899924966
cos(0) :
1.0
cos(math.pi) : -1.0
cos(2*math.pi) : 1.0
7)
Return Value
This method returns value of xy.
Example
The following example shows the usage of
pow() method.
#!/usr/bin/python
import math # This will import math module
print "math.pow(100, 2) : ",
math.pow(100, 2)
print "math.pow(100, -2) : ",
math.pow(100, -2)
print "math.pow(2, 4) : ",
math.pow(2, 4)
print "math.pow(3, 0) : ",
math.pow(3, 0)
When we run above program, it produces
following result:
math.pow(100, 2) : 10000.0
math.pow(100, -2) : 0.0001
math.pow(2, 4) : 16.0
math.pow(3, 0) : 1.0
8)
Description
The method sqrt() returns the square root
of x for x > 0.
Syntax
Following is the syntax for sqrt() method:
import math
math.sqrt( x )
Note: This function is not accessible
directly, so we need to import math module and then we need to call this
function using math static object.
Parameters
• x
-- This is a numeric expression.
Return Value
This method returns square root of x for x
> 0.
Example
The following example shows the usage of
sqrt() method.
#!/usr/bin/python
import math # This will import math module
print "math.sqrt(100) : ",
math.sqrt(100)
print "math.sqrt(7) : ",
math.sqrt(7)
print "math.sqrt(math.pi) : ", math.sqrt(math.pi)
When we run above program, it produces
following result:
math.sqrt(100) : 10.0
math.sqrt(7) : 2.64575131106
math.sqrt(math.pi) : 1.7724538509
Examples:
1)
f = 57
print(float(f))
2)
b = 125.0
c = 390.8
print(int(b))
print(int(c))
3)
user = "Sammy"
lines = 50
print("Congratulations, " + user
+ "! You just wrote " + lines + " lines of code.")
o/p:
Error
5)
lines_yesterday = "50"
lines_today = "108"
lines_more = int(lines_today) -
int(lines_yesterday)
print(lines_more)
o/p:
58
6)
total_points = "5524.53"
new_points = "45.30"
new_total_points = float(total_points) +
float(new_points)
print(new_total_points)
Output
5569.83
7)
f = "54.23"
print(int(f))
Output
ValueError: invalid literal for int() with
base 10: '54.23'
8)
flt_ans = 564.0 + 365.24
print(flt_ans)
Output
929.24
Boolean Data Type:
Booleans
The boolean data type can be one of two
values, either True or False. Booleans are used to represent the truth values
that are associated with the logic branch of mathematics, which informs
algorithms in computer science.
greater than
• 500
> 100 True
• 1
> 5 False
• less
than
• 200
< 400 True
• 4
< 2 False
• equal
• 5
= 5 True
• 500
= 400 False
Note:
long- holds long integers(exists in Python
2.x, deprecated in Python 3.x).
Complex :
c=100+3j
print("The type of variable having
value", c, " is ", type(c))
Example Interview Questions:
1. What is the output of print 0.1 + 0.2
== 0.3?
a) True
b) False
c) Machine dependent
d) Error
View Answer
Answer: b
Explanation: Neither of 0.1, 0.2 and 0.3
can be represented accurately in binary. The round off errors from 0.1 and 0.2
accumulate and hence there is a difference of 5.5511e-17 between (0.1 + 0.2)
and 0.3.
2. Which of the following is not a complex
number?
a) k = 2 + 3j
b) k = complex(2, 3)
c) k = 2 + 3l
d) k = 2 + 3J
View Answer
Answer: c
Explanation: l (or L) stands for long.
7. What is the result of cmp(3, 1)?
a) 1
b) 0
c) True
d) False
View Answer
Answer: a
Explanation: cmp(x, y) returns 1 if x >
y, 0 if x == y and -1 if x < y.
8. Which of the following is incorrect?
a) float(‘inf’)
b) float(‘nan’)
c) float(’56’+’78’)
d) float(’12+34′)
View Answer
Answer: d
Explanation: ‘+’ cannot be converted to a
float.
Interview Questions on Variables, Keywords
and Identifiers:
1
Which of the following is an invalid statement?
a) abc = 1,000,000
b) a b c = 1000 2000 3000
c) a,b,c = 1000, 2000, 3000
d) a_b_c = 1,000,000
View Answer
Answer: b
Explanation: Spaces are not allowed in
variable names.
2
Which of the following cannot be a variable?
a) __init__
b) in
c) it
d) on
View Answer
Answer: b
Explanation: in is a keyword.
3
Is Python case sensitive when dealing with identifiers?
a) yes
b) no
c) sometimes only
d) none of the mentioned
View Answer
Answer: a
Explanation: Case is always significant.
. What is the maximum possible length of
an identifier?
a) 31 characters
b) 63 characters
c) 79 characters
d) none of the mentioned
View Answer
Answer: d
Explanation: Identifiers can be of any
length.
4
Which of the following is invalid?
a) _a = 1
b) __a = 1
c) __str__ = 1
d) none of the mentioned
View Answer
Answer: d
Explanation: All the statements will
execute successfully but at the cost of reduced readability.
5
Which of the following is an invalid variable?
a) my_string_1
b) 1st_string
c) foo
d) _
View Answer
Answer: b
Explanation: Variable names should not
start with a number.
Comments
Post a Comment