Python Tuples
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 »
Create Tuple With One Item
To create a tuple with only one item, you
have to add a comma after the item,
otherwise Python will not recognize it as a
tuple.
Example
One item tuple, remember the comma:
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Try it Yourself »
Tuple Items - Data Types
Tuple items can be of any data type:
Example
String, int and boolean data types:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
Try it Yourself »
A tuple can contain different data types:
Example
A tuple with strings, integers and boolean
values:
tuple1 = ("abc", 34, True, 40, "male")
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 »
The tuple() Constructor
It is also possible to use
the tuple() constructor to make a tuple.
Example
Using the tuple() method to make a tuple:
thistuple =
tuple(("apple", "banana", "cherry")) #
note the double round-brackets
print(thistuple)
Try it Yourself »
Python Collections (Arrays)
There are four collection data types in the
Python programming language:
List is a collection which is ordered
and changeable. Allows duplicate
members.
Tuple is a collection which is ordered
and unchangeable. Allows duplicate
members.
Set is a collection which is unordered,
unchangeable*, and unindexed. No
duplicate members.
Dictionary is a collection which is
ordered** and changeable. No
duplicate members.
*Set items are unchangeable, but you can
remove and/or add items whenever you
like.
**As of Python version 3.7, dictionaries
are ordered. In Python 3.6 and earlier,
dictionaries are unordered.
Built-in Data Types
In programming, data type is an
important concept.
Variables can store data of different
types, and different types can do different
things.
Python has the following data types built-
in by default, in these categories:
Text str
Type:
Nume int, float, com
ric plex
Types:
Seque list, tuple, ran
nce ge
Types:
Mappi dict
ng
Type:
Set set, frozenset
Types:
Boole bool
an
Type:
Binary bytes, bytearr
Types: ay,
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 »
Definition and Usage
The range() function returns a sequence
of numbers, starting from 0 by default,
and increments by 1 (by default), and
stops before a specified number.
Syntax
range(start, stop, step)
Parameter Values
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)
Boolean Data Type in Python
Python Data type with one of the two
built-in values, True or False.
Boolean objects that are equal to True
are truthy (true), and those equal to
False are falsy (false).
However non-Boolean objects can be
evaluated in a Boolean context as well
and determined to be true or false. It is
denoted by the class bool.
Note – True and False with capital ‘T’
and ‘F’ are valid booleans otherwise
python will throw an error.
Example: The first two lines will print the
type of the boolean values True and
False, which is <class ‘bool’>. The third
line will cause an error, because true is
not a valid keyword in Python. Python is
case-sensitive, which means it
distinguishes between uppercase and
lowercase letters. You need to capitalize
the first letter of true to make it a
boolean value.
Python
print(type(True))
print(type(False))
print(type(true))
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.
Example: This code creates and prints a
variety of dictionaries. The first dictionary
is empty. The second dictionary has
integer keys and string values. The third
dictionary has mixed keys, with one string
key and one integer key. The fourth
dictionary is created using the dict()
function, and the fifth dictionary is
created using the [(key, value)] syntax
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.
Example: The code in Python is used to
access elements in a dictionary. Here’s
what it does, It creates a dictionary Dict
with keys and values as { 1: ‘Geeks’,
‘name’: ‘For’, 3: ‘Geeks’} . It prints the
value of the element with the key
‘name’ , which is ‘For’ . It prints the value
of the element with the key 3, which is
‘Geeks’ .
Dict = {1: ‘Geeks’, ‘name’: ‘For’, 3:
‘Geeks’}
Print(“Accessing a element using key:”)
Print(Dict[‘name’])
Print(“Accessing a element using get:”)
Print(Dict.get(3))
Output:
Accessing a element using key:
For
Accessing a element using get:
Geeks
Binary Types
In Python, bytes, bytearray,
and memoryview are used to work with binary
data and memory views of binary data. They
are essential for tasks like handling binary files,
network communication, and low-level data
manipulation.
The bytes is an immutable sequence type to
represent sequences of bytes (8-bit values).
Each element in a bytes object is an integer in
the range [0, 255]. We should use it for handling
binary data, such as reading/writing files,
network communication, or encoding/decoding
data.
Bytes are defined using the b prefix followed by
a sequence of bytes enclosed in single or
double quotes.
my_bytes = b'Hello, World!'
The bytearray is similar to bytes but
unlike bytes, bytearray objects can be
modified after creation. We use this to modify
binary data in place, such as when processing
binary files or network protocols.
Bytearrays are defined using
the bytearray() constructor, which accepts
an iterable.
my_bytearray = bytearray([72, 101, 108,
108, 111])
A memoryview type to create a “view” of
memory containing binary data. It doesn’t store
the data itself but provides a view into the
memory where the data is stored. These are
handy for efficiently manipulating large amounts
of data without copying it.
Memory views are typically used in advanced
scenarios where direct memory manipulation is
required, such as in high-performance
applications.
data = bytearray([1, 2, 3, 4, 5])
mem_view = memoryview(data)
None Type
The None represents a special value indicating
the absence of a value.
no_value = None
Mutable and immutable types
Data types in Python are categorized into
mutable and immutable data types.
Mutable data types are those whose values can
be changed, whereas immutable data types are
ones in which the values can’t be changed.
Python is one of the most popular programming
languages that offers a rich set of data types. A
Python data type defines the type of data stored
in a variable.
Unlike Java, C, and C++ in Python, we do not
specify the variable’s data type explicitly. The
data type in Python is automatically detected
when the value is stored in the variable.
Python data type is categorized into two types:
Mutable Data Type – A mutable data type is
one whose values can be changed.
o Example: List, Dictionaries, and Set
Immutable Data Type – An immutable data
type is one in which the values can’t be
changed or altered.
o Example: String and Tuples
Difference Between Mutable and Immutable
Data Type: Mutable vs Immutable
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.
Integer range in Python
What is the maximum possible value of
an integer in Python ?
Consider below Python program.
Python3
# 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 .
Thus we never need any special
arrangement for storing large numbers .
In Python 3, there is only one type “int”
for all type of integers. In Python 2.7.
there are two separate types “int” (which
is 32 bit) and “long int” that is same as
“int” of Python 3.x, i.e., can store
arbitrarily large numbers.
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))
Output in Python 2.7 :
<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
The Python range() works only with
integers. It doesn’t support the float type,
i.e., we cannot use floating-point/decimal
value in any of its arguments.
For example, If you use range() with float
step argument, you will get a TypeError
'float' object cannot be
interpreted as an integer.
for i in range(0, 1, 0.1):
print(i)
# Output TypeError: 'float' object
Use arange() and linspace() func
tions to use decimal numbers in a
start, stop and step argument to
produce a range of floating-point
numbers.
In Python, the range of float values
depends on the implementation and the
platform.
The Python language specification only
requires that floating-point numbers
support at least 1e-308 to 1e+308 with
a precision of at least 53 bits.
In practice, most modern Python
implementations use the IEEE
754 floating-point standard, which
provides a range of approximately 1.7e-
308 to 1.7e+308 with a precision of 53
bits. This range is the same on all
platforms and is supported by the float
built-in type.
The IEEE 754 standard defines the range
and precision of floating-point numbers
used by most modern programming
languages, including Python. The
standard defines two basic formats for
floating-point numbers
Single-precision format
It uses 32 bits and provides
approximately 7 decimal digits of
precision.
Double-precision format
It uses 64 bits and provides
approximately 16 decimal digits of
precision.
Python Arithmetic Operators
Arithmetic operators are symbols used to
perform mathematical operations on
numerical values. In most programming
languages, arithmetic operators include
addition (+), subtraction (-), multiplication
(*), division (/), and modulus (%).
Arithmetic Operators in Python
There are 7 arithmetic operators
in Python. The lists are given below:
Operato Synta
r Description x
Addition:
Addition adds two
+ x+y
Operator
operands
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
Modulus % Modulus: x%y
Operator returns the
remainder
when the
first
Operato Synta
r Description x
operand is
divided by
the second
Power
(Exponent):
Exponentiatio Returns
** first raised x ** y
n Operator
to power
second
Precedence of Arithmetic Operators
in Python
.
Operat Associativ
or Description ity
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
# using the subtraction operator
res = val1 - val2
print(res)
Output:
-1
Multiplication Operator
Python * operator is the multiplication
operator. It is used to find the product of
2 values.
Python
val1 = 2
val2 = 3
# using the multiplication operator
res = val1 * val2
print(res)
Output :
6
Division Operator
Python // operator is the division
operator. It is used to find the quotient
when the first operand is divided by the
second.
Python
val1 = 3
val2 = 2
# using the division operator
res = val1 / val2
print(res)
Output:
1.5
Floor Division Operator
The // in Python is used to conduct the
floor division. It is used to find the floor of
the quotient when the first operand is
divided by the second.
Python
val1 = 3
val2 = 2
# using the floor division
res = val1 // val2
print(res)
Output:
1
Modulus Operator
The % in Python is the modulus operator.
It is used to find the remainder when the
first operand is divided by the second.
Python
val1 = 3
val2 = 2
# using the modulus operator
res = val1 % val2
print(res)
Output:
1
Exponentiation Operator
In Python, ** is the exponentiation
operator. It is used to raise the first
operand to the power of the second.
Python
val1 = 2
val2 = 3
# using the exponentiation operator
res = val1 ** val2
print(res)
Output:
8
Python built-in function
Function Description
abs() Returns the
absolute value of
a number
all() Returns True if all
items in an
iterable object are
true
any() Returns True if any
item in an iterable
object is true
ascii() Returns a
readable version
of an object.
Replaces none-
ascii characters
with escape
character
bin() Returns the binary
version of a
number
bool() Returns the
boolean value of
the specified
object
bytearray() Returns an array
of bytes
bytes() Returns a bytes
object
callable() Returns True if the
specified object is
callable, otherwise
False
chr() Returns a
character from the
specified Unicode
code.
classmethod() Converts a
method into a
class method
compile() Returns the
specified source
as an object,
ready to be
executed
complex() Returns a complex
number
delattr() Deletes the
specified attribute
(property or
method) from the
specified object
dict() Returns a
dictionary (Array)
dir() Returns a list of
the specified
object's properties
and methods
divmod() Returns the
quotient and the
remainder when
argument1 is
divided by
argument2
enumerate() Takes a collection
(e.g. a tuple) and
returns it as an
enumerate object
eval() Evaluates and
executes an
expression
exec() Executes the
specified code (or
object)
filter() Use a filter
function to
exclude items in
an iterable object
float() Returns a floating
point number
format() Formats a
specified value
getattr() Returns the value
of the specified
attribute (property
or method)
globals() Returns the
current global
symbol table as a
dictionary
hasattr() Returns True if the
specified object
has the specified
attribute
(property/method)
hash() Returns the hash
value of a
specified object
help() Executes the built-
in help system
hex() Converts a
number into a
hexadecimal value
id() Returns the id of
an object
input() Allowing user
input
int() Returns an integer
number
isinstance() Returns True if a
specified object is
an instance of a
specified object
issubclass() Returns True if a
specified class is a
subclass of a
specified object
iter() Returns an iterator
object
len() Returns the length
of an object
list() Returns a list
locals() Returns an
updated dictionary
of the current
local symbol table
map() Returns the
specified iterator
with the specified
function applied to
each item
max() Returns the
largest item in an
iterable
memoryview() Returns a memory
view object
min() Returns the
smallest item in
an iterable
next() Returns the next
item in an iterable
object() Returns a new
object
oct() Converts a
number into an
octal
open() Opens a file and
returns a file
object
ord() Convert an integer
representing the
Unicode of the
specified
character
pow() Returns the value
of x to the power
of y
print() Prints to the
standard output
device
property() Gets, sets, deletes
a property
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
round() Rounds a numbers
set() Returns a new set
object
setattr() Sets an attribute
(property/method)
of an object
slice() Returns a slice
object
sorted() Returns a sorted
list
staticmethod() Converts a
method into a
static method
str() Returns a string
object
sum() Sums the items of
an iterator
super() Returns an object
that represents
the parent class
tuple() Returns a tuple
type() Returns the type
of an object