python-u1- datatypes
python-u1- datatypes
mytuple =
("apple", "banana", "cherry")
Tuple
Tuples are used to store multiple items in
a single variable.
Tuple is one of 4 built-in data types in
Python used to store collections of data,
the other 3 are List, Set, and Dictionary,
all with different qualities and usage.
A tuple is a collection which is ordered
and unchangeable.
Tuples are written with round brackets.
Example
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Try it Yourself »
Tuple Items
Tuple items are ordered, unchangeable,
and allow duplicate values.
Tuple items are indexed, the first item
has index [0], the second item has
index [1] etc.
Ordered
When we say that tuples are ordered, it
means that the items have a defined
order, and that order will not change.
Unchangeable
Tuples are unchangeable, meaning that
we cannot change, add or remove items
after the tuple has been created.
Allow Duplicates
Since tuples are indexed, they can have
items with the same value:
Example
Tuples allow duplicate values:
thistuple =
("apple", "banana", "cherry", "apple", "ch
erry")
print(thistuple)
Try it Yourself »
Tuple Length
To determine how many items a tuple
has, use the len() function:
Example
Print the number of items in the tuple:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
Try it Yourself »
type()
From Python's perspective, tuples are
defined as objects with the data type
'tuple':
<class 'tuple'>
Example
What is the data type of a tuple?
mytuple = ("apple", "banana", "cherry")
print(type(mytuple))
Try it Yourself »
Mappi dict
ng
Type:
Boole bool
an
Type:
range datatype
Example
Create a sequence of numbers from 0 to
5, and print each item in the sequence:
x = range(6)
for n in x:
print(n)
Try it Yourself »
Parame Descriptio
ter n
start Optional.
An integer
number
specifying
at which
position to
start.
Default is 0
stop Required.
An integer
number
specifying
at which
position to
stop (not
included).
step Optional.
An integer
number
specifying
the
incrementat
ion. Default
is 1
More Examples
Example
Create a sequence of numbers from 3 to
5, and print each item in the sequence:
x = range(3, 6)
for n in x:
print(n)
Try it Yourself »
Example
Create a sequence of numbers from 3 to
19, but increment by 2 instead of 1:
x = range(3, 20, 2)
for n in x:
print(n)
Output:
<class 'bool'>
<class 'bool'>
Traceback (most recent call last):
File
"/home/7e8862763fb66153d70824099d4f
5fb7.py", line 8, in
print(type(true))
NameError: name 'true' is not
defined
Set
Sets are used to store multiple items in a
single variable.
Set is one of 4 built-in data types in
Python used to store collections of data,
the other 3 are List, Tuple, and Dictionary,
all with different qualities and usage.
A set is a collection which
is unordered, unchangeable*,
and unindexed.
* Note: Set items are unchangeable, but
you can remove items and add new
items.
Sets are written with curly brackets.
Example
Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)
Try it Yourself »
Note: Sets are unordered, so you cannot
be sure in which order the items will
appear.
Set Items
Set items are unordered, unchangeable,
and do not allow duplicate values.
Unordered
Unordered means that the items in a set
do not have a defined order.
Set items can appear in a different order
every time you use them, and cannot be
referred to by index or key.
Unchangeable
Set items are unchangeable, meaning
that we cannot change the items after the
set has been created.
Once a set is created, you cannot change
its items, but you can remove items and
add new items.
Duplicates Not Allowed
Sets cannot have two items with the
same value.
Example
Duplicate values will be ignored:
thisset =
{"apple", "banana", "cherry", "apple"}
print(thisset)
Try it Yourself »
Note: The values True and 1 are
considered the same value in sets, and
are treated as duplicates:
Example
True and 1 is considered the same value:
thisset =
{"apple", "banana", "cherry", True, 1, 2}
print(thisset)
Try it Yourself »
Note: The values False and 0 are
considered the same value in sets, and
are treated as duplicates:
Example
False and 0 is considered the same value:
thisset =
{"apple", "banana", "cherry", False, True,
0}
print(thisset)
Try it Yourself »
Dictionary Data Type in Python
A dictionary in Python is an unordered
collection of data values, used to store
data values like a map, unlike other
Python Data Types that hold only a single
value as an element, a Dictionary holds a
key: value pair. Key-value is provided in
the dictionary to make it more optimized.
Each key-value pair in a Dictionary is
separated by a colon : , whereas each key
is separated by a ‘comma’.
Create a Dictionary in Python
In Python, a Dictionary can be created by
placing a sequence of elements within
curly {} braces, separated by ‘comma’.
Values in a dictionary can be of any
datatype and can be duplicated, whereas
keys can’t be repeated and must be
immutable.
The dictionary can also be created by the
built-in function dict().
An empty dictionary can be created by
just placing it in curly braces{}. Note –
Dictionary keys are case sensitive, the
same name but different cases of Key will
be treated distinctly.
Dict = {}
Print(“Empty Dictionary: “)
Print(Dict)
Dict = {1: ‘Geeks’, 2: ‘For’, 3: ‘Geeks’}
Print(“\nDictionary with the use of Integer
Keys: “)
Print(Dict)
Dict = {‘Name’: ‘Geeks’, 1: [1, 2, 3, 4]}
Print(“\nDictionary with the use of Mixed
Keys: “)
Print(Dict)
Dict = dict({1: ‘Geeks’, 2: ‘For’, 3:
‘Geeks’})
Print(“\nDictionary with the use of dict():
“)
Print(Dict)
Dict = dict([(1, ‘Geeks’), (2, ‘For’)])
Print(“\nDictionary with each item as a
pair: “)
Print(Dict)
Output:
Empty Dictionary:
{}
Dictionary with the use of Integer Keys:
{1: ‘Geeks’, 2: ‘For’, 3: ‘Geeks’}
Dictionary with the use of Mixed Keys:
{1: [1, 2, 3, 4], ‘Name’: ‘Geeks’}
Dictionary with the use of dict():
{1: ‘Geeks’, 2: ‘For’, 3: ‘Geeks’}
Dictionary with each item as a pair:
{1: ‘Geeks’, 2: ‘For’}
Accessing Key-value in Dictionary
In order to access the items of a
dictionary refer to its key name. Key can
be used inside square brackets. There is
also a method called get() that will also
help in accessing the element from a
dictionary.
None Type
The None represents a special value indicating
the absence of a value.
no_value = None
Mutabl Immuta
e ble
Data Data
type types
whose whose
values values
Definitio
can be can’t
n
change be
d after change
creatio d or
n. altered.
Memory Retains Any
Locatio the modific
n same ation
memor results
y in a
location new
even object
after and
the new
content memor
is y
modifie locatio
d. n
List,
Strings,
Exampl Diction
Types,
e aries,
Integer
Set
It is
It might
memor
be
y-
faster
efficient
in
, as no
some
new
scenari
Perform objects
os as
ance are
there’s
created
no
for
need to
frequen
track
t
change
change
s.
s.
When
When
you
you
want to
need to
ensure
modify,
data
Use- add, or
remain
cases remove
s
existing
consist
data
ent and
frequen
unalter
tly.
ed.
# A Python
program to
demonstrate that
we can store
# large numbers
in Python
x =
10000000000000000
00000000000000000
0000000000
x = x + 1
print (x)
Output :
10000000000000000000000000000000000
000000001
In Python, value of an integer is not
restricted by the number of bits and
can expand to the limit of the available
memory .
Python
# A Python
program to show
that there are
two types in
# Python 2.7 :
int and long int
# And in Python 3
there is only one
type : int
x = 10
print(type(x))
x =
10000000000000000
00000000000000000
0000000000
print(type(x))
<type 'int'>
<type 'long'>
Python3
# A Python3
program to show
that there are
two types in
# Python 2.7 :
int and long int
# And in Python 3
there is only one
type : int
x = 10
print(type(x))
x =
10000000000000000
00000000000000000
0000000000
print(type(x))
Output in Python 3 :
<type 'int'>
<type 'int'>
Float range in Python
Subtraction
Subtraction : subtracts
– two x–y
Operator
operands
Multiplicati
on:
Multiplication multiplies
* x*y
Operator
two
operands
Operato Synta
r Description x
Division
(float):
Division divides the
/ first x/y
Operator
operand by
the second
Division
(floor):
Floor Division divides the
// first x // y
Operator
operand by
the second
Power
(Exponent):
Exponentiatio Returns
** first raised x ** y
n Operator
to power
second
Exponentiation
** Operator right-to-left
Modulos,
%, Multiplication,
*, /, // Division, and Floor left-to-right
Division
Addition and
+, – Subtraction left-to-right
operators
Addition Operator
In Python, + is the addition operator. It is
used to add 2 values.
Python
val1 = 2
val2 = 3
# using the addition operator
res = val1 + val2
print(res)
Output:
5
Subtraction Operator
In Python, – is the subtraction operator. It
is used to subtract the second value from
the first value.
Python
val1 = 2
val2 = 3
Function Description
ascii() Returns a
readable version
of an object.
Replaces none-
ascii characters
with escape
character
chr() Returns a
character from the
specified Unicode
code.
classmethod() Converts a
method into a
class method
format() Formats a
specified value
getattr() Returns the value
of the specified
attribute (property
or method)
hex() Converts a
number into a
hexadecimal value
locals() Returns an
updated dictionary
of the current
local symbol table
oct() Converts a
number into an
octal
range() Returns a
sequence of
numbers, starting
from 0 and
increments by 1
(by default)
repr() Returns a
readable version
of an object
reversed() Returns a
reversed iterator
staticmethod() Converts a
method into a
static method