Python Unit 1 Notes
Python Unit 1 Notes
Python Basics, Objects- Python Objects, Standard Types, Other Built-in Types,
Internal Types, Standard Type Operators, Standard Type Built-in Functions,
Categorizing the Standard Types, Unsupported Types
Numbers - Introduction to Numbers, Integers, Floating Point Real Numbers,
Complex Numbers, Operators, Built- in Functions, Related Modules Sequences -
Strings, Lists, and Tuples, Mapping and Set Types
Python Objects
1. Introduction
• In Python, everything is an object.
• Objects are instances of a class (type).
• Each object has:
1. Identity – unique address in memory (id())
2. Type – the class of the object (type())
3. Value – the data stored in the object
Analogy: Think of an object as a real-world object (like a pen):
• Identity → serial number of the pen
• Type → pen type (ballpoint, gel)
• Value → color of ink
2. Creating Objects
• Objects are created automatically when you assign a value to a variable.
x = 10 # integer object
y = "Python" # string object
z = [1, 2, 3] # list object
• Check object type:
print(type(x)) # <class 'int'>
print(type(y)) # <class 'str'>
print(type(z)) # <class 'list'>
• Check object identity:
print(id(x)) # memory address of x
print(id(y))
Hence
• Everything in Python is an object.
• Objects have identity, type, and value.
• Understanding mutable vs immutable objects is crucial.
• Built-in functions like id(), type(), and isinstance() help inspect objects.
2. Numbers
• Used to represent numeric values.
• Types:
1. int – whole numbers
2. float – decimal numbers
3. complex – numbers with real and imaginary parts
Example:
a = 10 # int
b = 3.14 # float
c = 2 + 3j # complex
print(type(a)) # <class 'int'>
print(type(b)) # <class 'float'>
print(type(c)) # <class 'complex'>
3. Sequences
• Ordered collection of items
• Types:
1. String (str) – sequence of characters (immutable)
• s = "Python"
• print(s[0]) # P
• print(s[1:4]) # yth
2. List (list) – mutable sequence
• lst = [1,2,3]
• [Link](4)
• print(lst) # [1,2,3,4]
3. Tuple (tuple) – immutable sequence
• t = (1,2,3)
• print(t[1]) # 2
4. Mapping Type
• Dictionary (dict) – collection of key-value pairs (mutable)
student = {"name":"Ananth", "age":22}
print(student["name"]) # Ananth
student["age"] = 23 # update value
5. Set Types
• Set (set) – unordered collection of unique elements (mutable)
s = {1,2,2,3}
print(s) # {1,2,3}
[Link](4)
• Frozen Set (frozenset) – immutable set
fs = frozenset([1,2,3])
# [Link](4) # ERROR, cannot modify
6. Boolean Type
• Represents truth values: True or False
• Often result of comparisons:
a = 10
b=5
print(a > b) # True
print(a == b) # False
7. None Type
• Represents absence of a value: None
x = None
print(x) # None
print(type(x))# <class 'NoneType'>
int No a = 10
float No b = 3.14
complex No c = 2 + 3j
str No s = "Python"
tuple No t = (1,2,3)
frozenset No fs = frozenset([1])
NoneType No None
Key Points :
1. Standard types are predefined in Python.
2. Mutable vs Immutable is important for understanding behavior in programs.
3. Every object has type, identity, and value.
Other Built-in Types in Python
1. Introduction
• Besides the standard types (numbers, sequences, mappings, sets), Python
provides other built-in types to handle special purposes.
• These types are useful for working with binary data, ranges, memory, and
immutable sets.
3. Range
• Represents a sequence of numbers.
• Commonly used in loops.
r = range(5)
print(list(r)) # [0, 1, 2, 3, 4]
r2 = range(1, 10, 2)
print(list(r2)) # [1, 3, 5, 7, 9]
• Syntax: range(start, stop, step)
4. Memoryview
• Used to access memory of binary objects without copying.
• Efficient for large data handling.
b = bytes([10, 20, 30])
m = memoryview(b)
print(m[0]) # 10
• Note: Usually used in advanced programming (networking, file handling).
5. Frozenset
• Immutable version of a set.
• Cannot add or remove elements.
fs = frozenset([1,2,3,3])
print(fs) # frozenset({1,2,3})
# [Link](4) # ERROR: cannot modify
• Use: As keys in dictionaries (normal sets cannot be keys).
ba =
bytearray Yes Mutable version of bytes
bytearray([65,66])
2. Frame Objects
• Represent execution frames of Python code.
• Keep track of local variables, execution position, and call stack.
• Used in debugging, exception handling, and profiling.
import sys
def func():
frame = sys._getframe()
print(frame.f_code.co_name) # func
func()
3. Slice Objects
• Represent slices used in sequences.
• Used internally when you write [start:stop:step] in strings, lists, or tuples.
s = "Python"
slice_obj = slice(1,5,2)
print(s[slice_obj]) # 'yh'
• Equivalent to s[Link]
4. Ellipsis
• Represented by ...
• Used in advanced indexing, especially in NumPy arrays.
arr = [[1,2,3],[4,5,6]]
print(arr[...]) # [[1,2,3],[4,5,6]]
3. Key Points
1. Internal types are mostly used by Python itself.
2. Common ones: code objects, frame objects, slice objects, ellipsis.
3. Understanding these helps in debugging, slicing, and introspection.
4. Most beginners rarely create them directly, but slice objects are useful in
sequence operations.
Python Standard Type Operators
1. Introduction
• Operators in Python allow you to perform operations on objects.
• The behavior of operators depends on the object type.
• Common categories of operators:
1. Arithmetic
2. Relational (Comparison)
3. Logical
4. Assignment
5. Membership
6. Identity
2. Arithmetic Operators
• Used for mathematical calculations.
+ Addition 5+3=8
- Subtraction 5-3=2
* Multiplication 5 * 3 = 15
// Floor Division 5 // 2 = 2
% Modulus (remainder) 5 % 2 = 1
** Exponentiation 2 ** 3 = 8
Example:
a = 10
b=3
print(a + b) # 13
print(a // b) # 3
print(a ** b) # 1000
== Equal to 5 == 5 → True
Example:
x = 10
y = 20
print(x < y) # True
print(x == y) # False
4. Logical Operators
• Combine boolean expressions.
Example:
a=5
b = 10
print(a < 10 and b > 5) # True
print(not(a == b)) # True
5. Assignment Operators
• Used to assign values to variables.
= Assign a=5
Example:
x=5
x += 3
print(x) # 8
6. Membership Operators
• Check membership in sequences or sets.
7. Identity Operators
• Compare whether two objects are the same (same memory location).
Example:
a = [1,2,3]
b=a
c = [1,2,3]
print(a is b) # True (same object)
print(a is c) # False (different objects)
Key Points
1. Operators behave differently depending on object type.
2. Always know mutable vs immutable types when performing operations.
3. Logical, membership, and identity operators are important for conditional
statements.
1. Introduction
• Python provides a set of built-in functions that can be used on standard
types.
• They are ready to use and help perform common tasks like type conversion,
checking, calculations, and sequence operations.
isinstance(obj,
Checks if object is instance of class isinstance(5,int) → True
class)
Example:
x = [1,2,3]
print(type(x)) # <class 'list'>
print(id(x)) # memory address
print(isinstance(x,list))# True
3. Conversion Functions
Example:
x = "123"
y = int(x)
print(y + 10) # 133
4. Numeric Functions
Example:
nums = [10, 20, 30]
print(max(nums)) # 30
print(sum(nums)) # 60
print(divmod(10,3))# (3,1)
5. Sequence Functions
list(enumerate(['a','b'])) →
enumerate(seq) Returns (index,value) pairs
[(0,'a'),(1,'b')]
Example:
s = "Python"
for index, char in enumerate(s):
print(index, char)
6. Boolean Functions
Key Points
1. Built-in functions save time and reduce code complexity.
2. Functions are categorized: type/identity, conversion, numeric, sequence,
boolean.
3. Understanding these functions is essential for data manipulation and
calculations.
Categorizing the Standard Types in Python
1. Introduction
• Python standard types can be grouped based on:
1. Mutability – whether the object can be changed after creation.
2. Category – numbers, sequences, mappings, sets, and others.
• Understanding this helps in choosing the right type for a task and avoids
bugs.
3. Sequence Types
• Ordered collections: can be indexed and sliced.
• Immutable: str, tuple
• Mutable: list
Examples:
# Immutable sequence
t = (1,2,3)
s = "Python"
# Mutable sequence
lst = [1,2,3]
lst[0] = 100
print(lst) # [100,2,3]
4. Mapping Type
• Dictionary (dict) – key-value pairs, mutable.
• Example:
student = {"name":"Ananth","age":22}
student["age"] = 23 # modifying value
5. Set Types
• Set: mutable, unordered collection of unique elements
• Frozenset: immutable version of set
• Example:
s = {1,2,3}
[Link](4) # works
fs = frozenset([1,2,3])
# [Link](4) # ERROR
6. Numbers
• Always immutable.
• Types: int, float, complex
• Example:
x=5
y = x + 2 # creates new object, x is unchanged
Key Points
1. Mutable objects can be changed in place; immutable objects cannot.
2. Most sequences are either mutable (list) or immutable (tuple, str).
3. Sets and dictionaries are mutable, frozenset is immutable.
4. Numbers are always immutable.
Unsupported Types in Python
1. Introduction
• Python has many standard types, but not all operations are supported
between all types.
• Attempting unsupported operations will raise TypeError.
• Understanding this helps students avoid common runtime errors.
4. Set Operations
• Sets can only contain hashable types.
• Attempting to add mutable types (like list or dict) is unsupported.
s = set()
# [Link]([1,2,3]) # ERROR: TypeError
[Link]((1,2,3)) # Works
5. Unsupported Indexing
• Attempting to index non-sequence types is unsupported.
x = 10
# print(x[0]) # ERROR: TypeError
y = {1:"a"}
# print(y[0]) # ERROR: KeyError (wrong key)
Numbers in Python
1. Introduction
• In Python, numbers are a built-in standard type used to represent numeric
data.
• Python supports different numeric types:
1. Integer (int) – whole numbers
2. Floating Point (float) – decimal numbers
3. Complex (complex) – numbers with real and imaginary parts
• Key characteristics of numbers:
o Immutable: Once created, the value cannot be changed.
o Support arithmetic operations like addition, subtraction, multiplication,
etc.
o Can be converted between types using built-in functions.
2. Numeric Literals
• Numeric values can be written directly in code.
• Examples:
# Integer
x = 10
y = -5
z = 0b1010 # Binary literal (10 in decimal)
w = 0o12 # Octal literal (10 in decimal)
v = 0xA # Hexadecimal literal (10 in decimal)
# Floating Point
a = 3.14
b = -0.5
c = 2e3 # 2 × 10³ = 2000.0
# Complex
p = 2 + 3j
q = -1j
3. Immutability of Numbers
• Numbers are immutable objects.
• Any operation on a number creates a new object.
x=5
print(id(x)) # Memory address of x
x=x+2
print(id(x)) # New memory address (x now points to new object)
4. Type Conversion
• Numbers can be converted from one type to another using built-in functions:
a = 10 # int
b = float(a) # 10.0
c = complex(a) # (10+0j)
print(type(a)) # <class 'int'>
print(type(b)) # <class 'float'>
print(type(c)) # <class 'complex'>
Key Points
• Numbers are immutable objects in Python.
• Python supports integers, floats, and complex numbers.
• Numbers can be converted between types using int(), float(), complex().
• Numeric literals can include binary, octal, hexadecimal, and scientific
notation.
Integers in Python
1. Introduction
• Integer (int) is a numeric type representing whole numbers (no decimal
point).
• Can be positive, negative, or zero.
• Integers are immutable objects in Python.
Examples:
a = 10 # positive integer
b = -5 # negative integer
c=0 # zero
2. Integer Literals
• Integers can be written in different number systems:
Binary 0b or 0B 0b1010 10
Octal 0o or 0O 0o12 10
Hexadecimal 0x or 0X 0xA 10
Example:
x = 0b1101 # Binary → 13
y = 0o15 # Octal → 13
z = 0xD # Hex → 13
print(x, y, z) # 13 13 13
3. Operations on Integers
Python supports arithmetic operations:
a = 15
b=4
print(a + b) # 19 (Addition)
print(a - b) # 11 (Subtraction)
print(a * b) # 60 (Multiplication)
print(a / b) # 3.75 (Division → float)
print(a // b) # 3 (Floor Division)
print(a % b) # 3 (Modulus)
print(a ** b) # 50625 (Exponentiation)
4. Integer Functions
Python provides several built-in functions for integers:
Example:
n = -15
print(abs(n)) # 15
print(divmod(17,5)) # (3,2)
print(bin(10)) # 0b1010
5. Integer Properties
1. Immutable: Operations produce a new integer object.
x=5
print(id(x))
x=x+1
print(id(x)) # New memory address
2. Arbitrary precision: Python integers can be very large, limited only by
memory.
big = 123456789012345678901234567890
print(big * 2)
Key Points
1. Integers are whole numbers and immutable.
2. They support all arithmetic operations and conversion functions.
3. Python integers can be very large, unlike many other programming languages.
4. Understanding integer operations is foundational for working with numbers in
Python.
3. Operations on Floats
• Supports arithmetic operations similar to integers:
a = 5.5
b = 2.0
print(a + b) # 7.5
print(a - b) # 3.5
print(a * b) # 11.0
print(a / b) # 2.75
print(a // b) # 2.0 (floor division returns float)
print(a % b) # 1.5 (remainder)
print(a ** b) # 30.25 (exponentiation)
Key Points
1. Floats represent real numbers with decimals.
2. They support all arithmetic operations, similar to integers.
3. Floats are immutable objects.
4. Be aware of precision issues and use round() or decimal for exact calculations.
Complex Numbers in Python
1. Introduction
• Complex numbers are numbers with a real part and an imaginary part.
• In Python, the imaginary unit is represented by j or J.
• Complex numbers are immutable objects.
General form:
z = a + bj
where:
• (a) = real part
• (b) = imaginary part
Example:
z1 = 2 + 3j
z2 = -1 + 4j
print(z1, z2) # (2+3j) (-1+4j)
(2+3j).conjugate() → 2-
[Link]() Returns complex conjugate
3j
Example:
z = 3 + 4j
print(abs(z)) # 5.0
print([Link]()) # (3-4j)
5. Complex Number Properties
1. Immutable: Arithmetic creates new objects.
2. *Supports +, -, , /, and conjugate operations.
3. Cannot use floor division or modulus.
4. Useful for engineering, physics, and mathematics calculations involving
imaginary numbers.
Key Points
1. Complex numbers have real and imaginary parts.
2. Use complex(r,i) or a + bj to create them.
3. Python allows arithmetic operations, magnitude (abs()), and conjugate
(.conjugate()).
4. Floor division and modulus are unsupported.
2. Arithmetic Operators
+ Addition 5+3→8
- Subtraction 5-3→2
* Multiplication 5 * 3 → 15
// Floor Division 5 // 2 → 2
% Modulus (remainder) 5 % 2 → 1
** Exponentiation 2 ** 3 → 8
Example:
x = 10
y=3
print(x + y) # 13
print(x / y) # 3.3333333333333335
print(x ** y) # 1000
Note: Floor division (//) works for int and float but not complex.
3. Comparison Operators
• Compare numeric values and return True or False.
== Equal to 5 == 5 → True
Example:
a=7
b = 10
print(a < b) # True
print(a == b) # False
Note: Complex numbers cannot be compared with <, >, <=, >=. Only == and != are
allowed.
4. Assignment Operators
= Assign value x = 10
5. Logical Operators
• Logical operators are used in conditional checks with numbers:
` ` OR
^ XOR 5^3→6
~ NOT ~5 → -6
Example:
a = 5 # 0b0101
b = 3 # 0b0011
print(a & b) # 1 (0b0001)
print(a | b) # 7 (0b0111)
Note: Bitwise operators cannot be used with floats or complex numbers.
Key Points
1. Arithmetic operators: + - * / // % **
2. Comparison operators: == != < > <= >=
3. Logical operators: and, or, not
4. Assignment operators: =, +=, -=, *=, /=, //=, %=, **=
5. Bitwise operators: Only for integers.
6. Complex numbers cannot use <, >, <=, >=, //, % or bitwise operators.
Built-in Functions for Numbers in Python
1. Introduction
• Python provides many built-in functions to perform operations on numbers.
• These functions work for integers, floats, and in some cases complex
numbers.
• They are ready to use without importing any module.
Example:
z = 3 + 4j
print(abs(z)) # 5.0
print([Link], [Link]) # 3.0 4.0
print([Link]()) # (3-4j)
Key Points
1. abs(), round(), pow(), divmod() are useful for calculations.
2. Conversions like int(), float(), complex() allow type changes.
3. max(), min(), sum() help work with lists or sequences of numbers.
4. Complex numbers have .real, .imag, .conjugate() and can use abs().
5. Most functions are immutable, i.e., they do not change the original number.
Example:
import math
x=9
print([Link](x)) # 3.0
print([Link](5)) # 120
print([Link](3.14)) # 4
2. cmath Module
• Used for complex numbers.
• Functions include [Link](), [Link](), [Link](), etc.
Example:
import cmath
z = 2 + 3j
print([Link](z)) # (1.6741492280355401+0.8959774761298381j)
print(abs(z)) # 3.605551275463989
3. decimal Module
• For high precision floating point numbers.
• Avoids floating-point rounding errors.
Example:
from decimal import Decimal
a = Decimal('0.1')
b = Decimal('0.2')
print(a + b) # 0.3
4. fractions Module
• For rational numbers as fractions.
Example:
from fractions import Fraction
f1 = Fraction(3,4)
f2 = Fraction(1,2)
print(f1 + f2) # 5/4
Sequences – Strings
1. Introduction
• Strings are immutable sequences of characters in Python.
• Enclosed in single ' ', double " ", or triple quotes ''' ''' / """ """.
• Strings support indexing, slicing, and iteration.
Example:
s1 = "Python"
s2 = 'Hello'
s3 = """This is a multi-line
string."""
print(s1, s2)
2. String Operations
Length len("Python") 6
Example:
s = "Python"
print(s[0]) #P
print(s[1:4]) # yth
print(len(s)) # 6
print('t' in s) # True
3. Immutability
• Strings cannot be changed in-place. Any operation creates a new string:
s = "Python"
# s[0] = 'J' # ERROR
s = "J" + s[1:]
print(s) # Jython
Lists in Python
1. Introduction
• Lists are ordered, mutable sequences of elements.
• Elements can be of any type: numbers, strings, other lists, etc.
• Lists are defined using square brackets [].
Example:
# List of integers
numbers = [1, 2, 3, 4]
# List of mixed types
mixed = [1, "Hello", 3.14, True]
# Empty list
empty = []
print(numbers, mixed, empty)
2. List Operations
Indexing numbers[0] 1
Length len(numbers) 4
Example:
lst = [10, 20, 30, 40]
print(lst[1]) # 20
print(lst[-1]) # 40
print(lst[1:3]) # [20, 30]
print(lst + [50, 60]) # [10, 20, 30, 40, 50, 60]
3. Modifying Lists
• Lists are mutable, so elements can be changed, added, or removed.
Changing an element:
lst = [1,2,3]
lst[0] = 100
print(lst) # [100,2,3]
Adding elements:
[Link](4) # Adds 4 at end
[Link](1, 50) # Inserts 50 at index 1
print(lst) # [100,50,2,3,4]
Removing elements:
[Link](50) # Removes first occurrence of 50
[Link]() # Removes last element
del lst[0] # Deletes element at index 0
print(lst)
4. List Functions
5. Nested Lists
• Lists can contain other lists (2D or multidimensional lists).
matrix = [[1,2,3], [4,5,6], [7,8,9]]
print(matrix[0]) # [1,2,3]
print(matrix[1][2]) # 6
Key Points
1. Lists are ordered and mutable.
2. Support indexing, slicing, and iteration.
3. Can contain elements of any type.
4. Common operations: append, insert, remove, pop, sort, reverse.
5. Nested lists allow matrix-like structures.
Tuples in Python
1. Introduction
• Tuples are ordered, immutable sequences of elements.
• Unlike lists, tuples cannot be changed once created.
• Tuples are defined using parentheses () or simply commas.
Example:
# Tuple of integers
numbers = (1, 2, 3, 4)
# Tuple of mixed types
mixed = (1, "Hello", 3.14, True)
# Single element tuple
single = (5,)
# Empty tuple
empty = ()
print(numbers, mixed, single, empty)
2. Tuple Operations
Indexing numbers[0] 1
Length len(numbers) 4
Example:
t = (10, 20, 30, 40)
print(t[1]) # 20
print(t[-1]) # 40
print(t[1:3]) # (20, 30)
print(t + (50,60)) # (10,20,30,40,50,60)
3. Immutability
• Tuples cannot be modified: no element assignment, deletion, or append.
t = (1,2,3)
# t[0] = 100 # ERROR
# [Link](4) # ERROR
# You can create a new tuple instead
t = (100,) + t[1:]
print(t) # (100, 2, 3)
4. Tuple Functions
5. Nested Tuples
• Tuples can contain other tuples (or lists) for multi-dimensional data:
nested = ((1,2,3), (4,5,6), (7,8,9))
print(nested[0]) # (1,2,3)
print(nested[1][2]) # 6
6. Tuple vs List
Syntax () []
Key Points
1. Tuples are ordered, immutable sequences.
2. Support indexing, slicing, and iteration.
3. Useful for fixed data or multiple return values.
4. Can contain mixed types and nested structures.
5. Slightly faster than lists due to immutability.
3. Modifying Dictionaries
• Add or update key-value pairs:
student["age"] = 21 # Update existing key
student["roll_no"] = 101 # Add new key
print(student)
• Remove elements:
[Link]("grade") # Removes key 'grade'
del student["roll_no"] # Deletes key 'roll_no'
[Link]() # Clears all key-value pairs
4. Dictionary Operations
Example:
student = {"name": "Alice", "age": 20}
print([Link]()) # dict_keys(['name','age'])
print([Link]()) # dict_values(['Alice',20])
print([Link]()) # dict_items([('name','Alice'),('age',20)])
5. Nested Dictionaries
• Dictionaries can contain other dictionaries for structured data:
school = {
"class1": {"name": "Alice", "age": 10},
"class2": {"name": "Bob", "age": 11}
}
print(school["class1"]["name"]) # Alice
Key Points
1. Dictionaries are unordered, mutable collections of key-value pairs.
2. Keys must be immutable and unique, values can be any type.
3. Useful for mapping one value to another (like name → age).
4. Supports access, update, delete, and iteration over keys, values, or items.
5. Nested dictionaries allow hierarchical data storage.
Set Types in Python
1. Introduction
• Sets are unordered collections of unique elements.
• They are mutable, but elements must be immutable (numbers, strings,
tuples).
• Sets do not allow duplicates.
• Defined using curly braces {} or the set() function.
Example:
# Creating sets
numbers = {1, 2, 3, 4, 4, 5} # Duplicate 4 is removed
letters = set(['a','b','c','a']) # Duplicate 'a' removed
print(numbers) # {1, 2, 3, 4, 5}
print(letters) # {'a', 'b', 'c'}
• Empty set must be created using set(), not {} (which creates an empty
dictionary).
empty_set = set()
print(empty_set) # set()
2. Set Operations
Sets support mathematical operations like union, intersection, difference, and
symmetric difference.
A = {1,2,3,4}
B = {3,4,5,6}
print(A | B) # Union → {1,2,3,4,5,6}
print(A & B) # Intersection → {3,4}
print(A - B) # Difference → {1,2}
print(A ^ B) # Symmetric Difference → {1,2,5,6}
3. Modifying Sets
Example:
A = {1,2,3}
[Link](4)
[Link](2)
print(A) # {1, 3, 4}
4. Set Membership
• Check if an element exists in a set:
fruits = {"apple","banana","cherry"}
print("apple" in fruits) # True
print("orange" not in fruits) # True
5. Set Comparison
• Subset, Superset, and Disjoint:
A = {1,2,3}
B = {1,2,3,4,5}
print([Link](B)) # True
print([Link](A)) # True
print([Link]({4,5})) # True
Key Points
1. Sets are unordered, mutable collections with unique elements.
2. Support mathematical operations: union (|), intersection (&), difference (-),
symmetric difference (^).
3. Elements can be added, removed, or updated.
4. Useful for removing duplicates, membership tests, and set operations.
5. Empty set must be created using set(), not {}.