0% found this document useful (0 votes)
8 views57 pages

Python Basic

The document provides an overview of Python, a high-level programming language, detailing its features, how it works, and key concepts such as identifiers, constants, variables, and data types. It explains the use of functions like print() and input(), various operators, control flow statements, loops, and data structures including lists, tuples, and dictionaries. Additionally, it covers string manipulation methods and the distinction between mutable and immutable types in Python.

Uploaded by

rakhade1209
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views57 pages

Python Basic

The document provides an overview of Python, a high-level programming language, detailing its features, how it works, and key concepts such as identifiers, constants, variables, and data types. It explains the use of functions like print() and input(), various operators, control flow statements, loops, and data structures including lists, tuples, and dictionaries. Additionally, it covers string manipulation methods and the distinction between mutable and immutable types in Python.

Uploaded by

rakhade1209
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

​​ ​ ​ ​ Python

Python is a general-purpose interpreted, interactive, object-oriented,


and high-level programming [Link] contains features of both C
and Java programming language.

Python is a case sensitive programming language.

How Python work:

source code/program------>bytecode------>binary/machine
code---->computer
([Link]) ([Link])
(output)

PVM(python virtual machine) interpreter: convert byte code into


machine code
-

Identifier:

“An identifier is a name given to an entity”.

1.​Identifier is a user-defined name given to a variable, a function, a


class, a module, or any other object.

Examples of a valid identifier:


●​ num1
●​ FLAG
●​ get_user_name
●​ userDetails
●​ _1234

2.​An identifier cannot start with a [Link] 1num.

3.​cannot use special symbols in the identifiers [Link]


like ( !, @, #, $, %, . ) are [Link] num$1.

4.​A keyword cannot be used as an identifier. In Python, keywords


are the reserved names that are built-in in Python.

Constant:
A constant is an identifier whose values cannot be changed
throughout the execution of the program whereas variable values
keep on changing.

There are no constants in Python, the way they exist in C and


Java.

We can define a constant written in all capital letters separating


words with _ .But defined constants are not actually a constant just
for remembering we define constants in capital letters.

Variable:
In python variables are considered as a tag and values are considered
as objects. In python, memory is allocated to the values instead of
variables. While in C and Java memory is allocated to the variable not
to the values.
Every variable name should start with alphabet or underscore(_)
No space are allowed in variable declaration
Except underscore(_) no other special symbol are allowed in the
middle of variable declaration
No reserved keyword can be use a variable name
Note:- In python memory allocated to the values, while in C and Java
memory is allocated to the variable.

>>>a=100
>>> id(a)
8791191328816
>>> b=100
>>> id(b)
8791191328816
In the above example both a and b have the same memory address
because in python memory is allocated to the values instead of
variables. Due to which less memory is utilized. While in C and Java
each variable is allocated a different memory address.
>>> a= 100
>>> a=200
>>> print(a)
>>>200
In this example first we assign value 10 to the variable a after that we
assign 20 to the variable b. As we discuss, python allocates memory
to the address not to the variable. As value 10 has no tag variable as
variable a given the value 20, so value 10 will become useless and it
will be deleted by the garbage collector in python.

print() function:

print(*objects, sep=' ', end='\n', file=[Link],


flush=False)

file: This is an optional parameter that specifies the file where you
want to print the output. By default, it's set to `[Link]`, which
means it prints to the standard output (usually the console).

flush: This is an optional parameter that, when set to `True`, forces the
output to be flushed immediately. By default, it's set to `False`.

Type Conversion:

In Python, data type conversion, also known as type casting, can be


performed explicitly and implicitly.

1. Implicit Type Conversion (Automatic Type Conversion):


Implicit type conversion occurs automatically when Python converts
one data type to another without any direct action from the
programmer.
2. Explicit Type Conversion (Type Casting):
Explicit type conversion, also known as type casting, involves the
programmer explicitly converting one data type to another. You
can use built-in functions like `int()`, `float()`, `str()`, and others to
convert between data types. This is useful when you want to control
the type conversion or when it's not happening automatically, and you
want to ensure compatibility.

Explicit type conversion:

int(x): Converts `x` to an integer.


float(x): Converts `x` to a floating-point number.
str(x): Converts `x` to a string.
bool(x): Converts `x` to a boolean value.
list(x): Converts `x` to a list.
tuple(x): Converts `x` to a tuple.
set(x): Converts `x` to a set.
bin(x): Convert ‘x’ to a binary

input() function:
In Python, you can get input from the user using the `input()` function.

input() function always returns the user's input as a string. If you


need the input in a different data type, like an integer or a float, you
should perform explicit type conversion after using input().
It stops the flow of the program until the user input the details.
Operators:
[Link] Arithmetic Operator

In the floor division // rounds the result down to the nearest whole
number
[Link] Comparison Operator

In comparison /Relational operators result is in the form of True or


False.
eg:x = 5
y=3
print(x == y)
o/p - False
returns False because 5 is not equal to 3
[Link] Logical Operator

In logical operators the result is in the form of True or False.

—-----------AND Operator—----------
True and Expression=Expression
False and Expression= False
True and Expression1 and Expression2 = Expression2
False and Expression1 and Expression2 = False

—-----------OR Operator—----------
True or Expression = True
False or Expression = Expression
True or Expression1 or Expression2 = True
False or Expression1 or Expression2 = Expression1

>>> a = 10
>>> b = 20
>>> c = 30
>>> print(a<b and c)
o/p- 30
>>> a = 10
>>> b = 20
>>> c = 30
>>> d = 40
>>> print(a<b and c and d)
o/p- 40
>>> a = 10
>>> b = 20
>>> c = 30
>>> d = 40
>>> print(a<b and a<d and c)
o/p- 30
[Link] Operators:
[Link] Operators:
[Link] Membership Operators:

[Link] Identity Operators:

Same will be for is not.


Operator precedence :

Operator precedence : which operator executes first while execution,


like BODMAS in mathematics the same way in python there is
PEMDAS.
If statement:

Syntax
if condition:
# Code to be executed if the condition is True

If the condition is true then only the block of statements inside the if
statement will be executed.

If else statement:

Syntax
if condition:
# Code to be executed if the condition is True
else:
# Code to be executed if the condition is False

If the condition is true then only the block of statements inside the if
statement will be executed otherwise the else part will be executed.

If-elif statement:

Syntax
if condition1:
# Code to be executed if condition1 is True
elif condition2:
# Code to be executed if condition2 is True
elif condition3:
# Code to be executed if condition3 is True
# ...
else:
# Code to be executed if none of the conditions are True

The if-elif (short for "else if") statement in Python allows you to
evaluate multiple conditions and execute different blocks of code
based on the first condition that is True.

If the condition is true then only the block of statements inside the if
statement will be executed otherwise the elif part will be executed
If all conditions are false then lastly the else part will be executed.

While loop:

The `while` loop in Python is used to repeatedly execute a block of


code as long as a specified condition is `True`.

Syntax
while condition:
# Code to be executed as long as the condition is True

It's important to be cautious with `while` loops to avoid infinite loops,


where the condition is always `True`, leading to continuous execution.
To prevent this, ensure that the condition becomes `False` at some
point to exit the loop.

range() function:

The `range()` function in Python is used to generate a sequence of


numbers. It is often used in combination with loops, especially with
the `for` loop, to iterate over a sequence of numbers. The `range()`
function can be used in three different ways:

1. range(stop): Generates a sequence of numbers from 0 up to (but


not including) the specified `stop` value.
2. range(start, stop): Generates a sequence of numbers from the
`start` value up to (but not including) the `stop` value.
3. range(start, stop, step): Generates a sequence of numbers
starting from the `start` value, up to (but not including) the `stop`
value, with the specified `step` increment.

The range() function is a useful way to generate a sequence of


numbers for iterations and other operations.

For loop:
A `for` loop in Python is used to iterate over a sequence (such as a
list, tuple, string, or range) or any other iterable object.

Syntax
for variable in iterable:
# Code to be executed in each iteration
for: It is the keyword that starts the loop.

variable: This is a variable that takes the value of each item in the
iterable during each iteration.

in: It is the keyword used to specify the iterable.

iterable: This is the collection or sequence of items that the loop will
iterate over.

Code block: The indented block of code following the `for` statement is
executed in each iteration, with the `variable` taking on the value of
the current item from the iterable.

Break statement:
The `break` statement in Python is used to exit or terminate a loop
prematurely. It is commonly used within loops, such as `for` or `while`
loops, to immediately stop the loop's execution and exit it, even if the
loop's termination condition has not been met.

Syntax:
for variable in iterable:
if condition:
break

Or for a while loop:

Syntax:
while condition:
if condition:
break

Continue Statement:
In Python, the `continue` statement is used inside loops (like `for` and
`while` loops) to skip the current iteration and proceed to the next
iteration of the loop.

Syntax:

for variable in sequence:


if condition:
continue

Datatype:
Datatype represents the type of data stored into a variable or memory.

There are two type of datatype:


●​ Built-in datatype
●​ User-defined datatype

Built-in Datatype:
1.​None type
2.​Numeric type
3.​Sequences
4.​Sets
5.​Mapping
User-defined datatype:
1.​Array
2.​Class
3.​Module

1. None Type:

It is a datatype represent an object that doesn’t contain any value.(In


java we read as a Null)
2. Numeric type /Number:
●​ Int - Int datatype represent an integer number. integers are zero,
positive or negative whole numbers without a fractional part
and having unlimited precision, e.g. 0, 100, -10. There is no limit
for the size of an int datatype

●​ Float - Float datatype represent an floating point number. It is a


number that contains decimal points. eg: 0.5, 1.23 etc.

●​ Complex - Complex numbers are written in the form, x + yj ,


where x is the real part and y is the imaginary part. j or J value is
square root of -1.

●​ Bool Type: Bool datatype represents boolean value True or


False. Python internally represents True as 1 and False as 0.
3. Sequence Type:
●​ String - String represents a single or group of characters. String
are enclosed in single or double quotes eg: “hello”, ‘hello’.

●​ List - A list is a group of elements. A list can store different types


of elements which can be modified. Lists are dynamic which
means size is not fixed. Lists are represented using square
brackets[ ].eg. [10, -20, 2.3, ‘hello’].List items are indexed, the
first item has index [0], the second item has index [1] etc. Lists
have a defined order, and that order will not [Link] we add
new items to a list, the new items will be placed at the end of
the list. Lists allowed duplicates of data. We can also access
data by negative indexing starting from [-1],[-2] etc.

●​ Tuple - A tuple contains a group of elements which can be


different types. It is similar to List but tuples are read
only(immutable) which means we cannot modify its elements.
Tuples are represented using parentheses ( ). Tuple allow
duplicates.

●​ Range - Range represents a sequence of numbers. The


numbers in the range are immutable. Eg: rg =range(5) o/p
01234. The elements can be accessed through indexing.
4. Sets:
●​ 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.
●​ In sets duplicates are not allowed.
●​ Sets are written with curly brackets

5. Mapping type/ dict/ dictionary:


●​ Dictionaries are used to store data values in key:value pairs.
●​ A dictionary is a collection which is ordered*, changeable and do
not allow [Link] of Python version 3.7, dictionaries are
ordered. In Python 3.6 and earlier, dictionaries are
unordered.
●​ Dictionaries are written with curly brackets, and have keys and
values:
Note: In python there is no concept of char datatype to represent a
single character.

Mutable And Immutable:

Mutable:
In Python, the term "mutable" refers to objects that can be modified
or changed after they are created.
●​ List
●​ Sets
●​ Dictionaries
●​ User defined Classes

Immutable:
In Python, "immutable" refers to objects that cannot be modified or
changed after they are created.

●​ Strings
●​ Tuples
●​ Integers, floats, booleans
●​ Immutable sets (frozensets):

E.g. my_frozenset = frozenset({1, 2, 3})


String:
In Python, a string is a sequence of characters enclosed within either
single quotes (`'`) or double quotes (`"`). Strings are used to represent
text or a sequence of characters, and they are one of the fundamental
data types in Python.
str datatype represent string datatype

1. Creating Strings:
You can create strings using single or double quotes. For example:

string1 = 'This is a string.'


string2 = "This is another string."

2. String Concatenation:
You can concatenate (combine) strings using the `+` operator:

full_string = string1 + " " + string2

3. String Length:
You can find the length of a string using the `len()` function:

length = len(my_string)
4. String Slicing:
str[start:end:step]: Slices the string from the 'start' index to 'end'
index.
str[:end]: Slices from the beginning to the 'end' index.
str[start:]: Slices from the 'start' index to the end.
step: An optional parameter indicating the step size, i.e., how many
characters to skip. If omitted, it defaults to 1.

5. Basic String Operations:


●​ +: Concatenation
●​ *: Repetition
●​ len(): Returns the length of the string

String Method:

Python provides a wide range of string functions and methods that you
can use to manipulate strings.
Commonly used string functions and methods:

●​ [Link](): Converts the string to uppercase.

●​ [Link](): Converts the string to lowercase.

●​ [Link](): Capitalizes the first character.


●​ [Link](): Capitalizes the first character of each word.

●​ [Link](): Removes leading and trailing whitespace. By default it


removes all spaces.

●​ [Link](): Removes leading whitespace from left.

●​ [Link](): Removes trailing whitespace from right.

●​ [Link](substring): Checks if the string starts with a given


substring.

●​ [Link](substring): Checks if the string ends with a given


substring.

●​ [Link](old, new): Replaces all occurrences of 'old' with 'new'.

●​ [Link](value): count method is a built-in method for sequences


such as strings, lists, and tuples. It is used to count the number of
occurrences of a specified element within the sequence.

●​ [Link](value, start, end):


The find() method finds the first occurrence of the specified
value.
The find() method returns -1 if the value is not found.
The find() method is almost the same as the index()method, the
only difference is that the index() method raises an exception
if the value is not found.

●​ [Link](value, start, end): The rfind() method finds the last


occurrence of the specified value.
The rfind() method returns -1 if the value is not found.
The rfind() method is almost the same as the rindex()method,
the only difference is that the rindex() method raises an
exception if the value is not found.

●​ [Link](delimiter, maxsplit):
Splits the string into a list of substrings using the delimiter.
delimiter is the character or substring at which the string
should be split. It is an optional parameter, and if not provided,
it defaults to splitting at whitespace (spaces, tabs, and
newline characters).
maxsplit is also an optional parameter that determines the
maximum number of splits to make. If not provided, or set to
-1, it will split the string as many times as possible.

●​ separator_string.join(iterable):
The join method in Python is used to concatenate elements of
an iterable (e.g., a list, tuple, or string) into a single string,
using a specified separator. It is the inverse operation of the
split method.
separator_string is the string that you want to use as a
separator between the elements of the iterable.
iterable is the collection of elements you want to join together.
●​ [Link](): Checks if the string consists of only digits.

●​ [Link](): Checks if the string consists of only alphabetic


characters.

●​ [Link](): Checks if the string consists of alphanumeric


characters.

●​ [Link](): Checks if all characters are lowercase.

●​ [Link](): Checks if all characters are uppercase.

●​ [Link](): Checks if the string consists of only numeric


characters, also consider numeric data from the other language.

●​ [Link](): Built-in string method that is used to swap the


case of each character in a string. It converts lowercase characters
to uppercase and uppercase characters to lowercase while
leaving non-alphabetic characters unchanged.
Function:
Function is a block of organized, reusable code that performs a
specific task. It's a set of instructions that you can use over and over
again to perform a specific task.

Types of functions:

Built-in Functions:
Python provides a set of built-in functions that are always available
for you to use. Examples include `print()`, `len()`, `input()`, and
`type()`. These functions serve general purposes and are part of the
Python standard library.

User-Defined Functions:
You can create your own functions using the `def` keyword. These
functions are defined by you to perform specific tasks as needed in
your program. User-defined functions allow you to encapsulate logic
and promote code reusability.

1. Function Definition:

def function_name(parameters):
"""Optional docstring"""
# Function code
# ...

def: This keyword is used to define a function.


function_name: Giving valid name to the function, by which we can
know which operation it can perform
parameters: This is a list of input arguments that the function
expects. Parameters are enclosed in parentheses and separated by
commas. You can have zero or more parameters.

"""Optional docstring""":To describe what the function does. It's


good practice to provide clear and informative documentation for your
functions.
# Function code: This is the block of code that performs the task or
operation of the function. It should be indented under the `def`
statement.

2. Function Call:

To use the function, you call it by its name, passing any required
arguments:

print( function_name(arguments))

function_name: Replace this with the actual name of your function.


arguments: Provide the values that correspond to the parameters
defined in the function. If the function doesn't have any parameters,
you can call it without any arguments.

Parameter And Argument:


Parameter:
A parameter is a variable or name declared in the function definition.
It acts as a placeholder for an argument.

def greet(name): # Here, 'name' is a parameter.


print(f"Hello, {name}!")

Argument:

An argument is the actual value or expression that you pass to a


function when calling it.

greet("John") Here, "John" is an argument passed to the 'John'

Nested Function:
Nested functions in Python refer to defining one function within
another function. The inner function has access to the variables and
scope of the outer function. This concept is often used to encapsulate
functionality or create helper functions within a larger function.

Passing function as a parameter:


In Python, you can pass a function as a parameter to another function,
which allows you to create more flexible and reusable code.
Functions that accept other functions as arguments are often
referred to as higher-order functions.
Argument:

Actual Argument And Formal Argument:

1. Actual Argument (Actual Parameter):


- An actual argument in Python is the value or expression that is
provided as an input when calling a function or method.
- Actual arguments can be constants, variables, expressions, or the
results of other function calls.

For example, in the function call `add(3, 5)`, the values `3` and `5` are
the actual arguments.

2. Formal Argument (Formal Parameter):


- A formal argument in Python is the name used in the function or
method definition to represent a placeholder for an actual argument.

Example:
def add(a, b): # In the add function, a and b are formal arguments.
return a + b

result = add(3, 5) # Here, 3 and 5 are actual arguments.


print(result)

Type of Arguments:

In Python, actual arguments can take various forms, depending on the


specific needs of your function or method. The type of actual
arguments can be categorized as follows:
1. Positional Arguments:
- Positional arguments are the most common type of actual
arguments in Python.
- They are matched to formal parameters based on their
position in the function or method call.

2. Keyword Arguments:
- Keyword arguments are actual arguments specified using the
parameter names in the function or method call.
- They allow you to pass arguments in any order as long as you
associate them with the correct formal parameters using their names.

3. Default Arguments:
- Default arguments are values assigned to formal parameters in the
function or method definition.
- If you don't provide a corresponding actual argument for a default
parameter, the default value is used.

4. Variable length argument:( *args (Arbitrary Positional Arguments) ):


- The `*args` parameter allows a function to accept an arbitrary
number of positional arguments as a tuple.
- You can use `*args` when you want to handle an unspecified
number of non-keyword arguments.

[Link] Variable length argument: (** kwargs (Arbitrary Keyword


Arguments) ):
- The `kwargs` parameter allows a function to accept an arbitrary
number of keyword arguments as a dictionary.
- You can use `kwargs` when you want to handle an unspecified
number of keyword arguments.

Lambda Function:

In Python, an anonymous function is also known as a lambda function.


Lambda functions are small, unnamed functions that can have any
number of arguments but can only have one expression. They are
often used for short, simple operations that can be defined in a single
line of code.

Syntax:

lambda arguments: expression

Nested lambda function:


In many programming languages, including Python, you can create
nested lambda expressions, which means you can define a lambda
function inside another lambda function.

Syntax :

outer_lambda = lambda argument1: (lambda argument2:


expression)(argument1)

outer_lambda is the outer lambda function.


argument1 is the argument for the outer lambda function.
argument2 is the argument for the inner lambda function.
expression is the code or expression that the inner lambda function
operates on.

Local variable:
In Python, a local variable is a variable that is defined within a
specific scope, such as within a function or a block of code. Local
variables have limited visibility, and they are only accessible
within the scope in which they are defined.

If you try to access it outside the function, it will result in a


NameError because the variable is out of scope.

Global Variable:
Variables defined in the global scope are accessible from
anywhere within the script or module. They are not confined to
any specific function or code block and can be used globally
throughout the program.

Global keyword:
In Python, the global keyword is used to indicate that a variable
declared within a function should be treated as a global variable
rather than a local variable. When you create a variable inside a
function without using the
global keyword, it is considered a local variable, which
means it is only accessible within that function's scope.

Globals Function:
In Python, the globals() function is a built-in function that
returns a dictionary representing the current global
symbol table. This dictionary contains all global variables
and their values in the current module, including both
variables and functions.

Recursive function:
A recursive function in programming is a function that calls itself
to solve a problem. A recursive function is like a task that breaks
itself into smaller, similar tasks until it's easy enough to solve.

In a recursive function, there are typically two parts:


●​ Base Case: This is the condition under which the recursion
stops. When the base case is met, the function returns a
specific value without making another recursive call.
●​ Recursive Case: This is where the function calls itself with
modified arguments to solve a smaller instance of the same
problem. The idea is that each recursive call gets closer to
the base case, and eventually, the base case is reached.
Decorator:

A decorator in Python is a design pattern and a powerful feature


that allows you to modify or extend the behavior of functions
or methods without changing their source code.
Decorators are implemented as functions that take another
function as an argument, extend the behavior of that function, and
then return the original or a modified function.
Decorators are often denoted with the "@" symbol in Python.

List:

In Python, a list is a data structure that allows you to store a


collection of items.
●​ Lists are ordered.
●​ List are mutable.
●​ Lists can contain elements of different data types, and these
elements are separated by commas and enclosed in square
brackets [].
●​ Lists are represented using [] brackets.

List Method:

Python provides a variety of built-in methods for working with lists.


Here's a list of some commonly used list methods:

1. append(x): Adds an element `x` to the end of the list.


2. extend(iterable): Appends all the elements from an iterable (e.g.,
another list) to the end of the list.

3. insert(i, x): Inserts element `x` at index `i`,and moves the current
element forward but does not replace the elements.

4. remove(x): Removes the first occurrence of element `x` from the list.

5. pop([i]): Removes and returns the element at index `i`. If `i` is not
specified, it removes and returns the last element.

6. clear(): Removes all elements from the list, making it empty.

7. index(x[, start[, end]]): Returns the index of the first occurrence of


element `x` within the specified slice `[start:end]`. Raises a `ValueError` if
`x` is not found.

8. count(x): Returns the number of times element `x` appears in the list.

9. sort(key=None, reverse=False): Sorts the list in ascending order. You


can customize the sorting behavior using the `key` function and specify
`reverse=True` for descending order.

10. reverse(): Reverses the order of elements in the list.


11. copy(): Returns a shallow copy of the list (a new list with the same
elements).

12. len(): Returns the number of elements in the list.

Slicing of List:
In Python, slicing is a way to extract a portion of a list, string, or other
sequence types.

Syntax:
my_list[start:stop:step]

start: The index where the slice begins (inclusive).


stop: The index where the slice ends (exclusive).
step: The step or increment between elements in the slice (default is
1).

Concatenation of list:
In Python, you can concatenate lists using the + operator or by using
the extend() method.

Repetition of list:
If we want to create a list by repeating its elements, we can use the *
operator in Python. This operator allows you to repeat the elements
of a list a certain number of times.
Aliasing of list:
Aliasing in the context of lists refers to creating multiple references
(aliases) to the same list object. When you create an alias for a list
and modify the content of the list through one reference, the
changes will be reflected in all other references to the same list.

Coping of list:
In Python, when we need to create a copy or clone of a list, there are
two types of copy:

1. Shallow Copy:

A shallow copy creates a new object but does not create copies of
nested objects. Instead, it copies references to the nested
objects. We can use the `copy()` method or the `[:]` slice notation to
create a shallow copy.

2. Deep Copy:

A deep copy creates a completely independent copy of the


original list and all its nested objects. You can use the
`[Link]()` method from the `copy` module.

Note: If your list contains nested mutable objects, a deep copy


may be necessary to avoid unintended modifications.
Nested List:
In Python, a nested list is a list that appears as an element in
another list. This means you have lists within lists. Each inner list is
considered a separate element of the outer list.

List Function:
There is also a built-in list() function in Python. This function can be
used to convert other iterable objects (like strings, tuples, or
sets) into a list.

Tuple:

1. Definition and Syntax:


- A tuple is a collection data type that is similar to a list.
- It is defined using parentheses ().

my_tuple = (1, 2, 3, 'a', 'b')

2. Immutable Nature:
- Tuples are immutable, meaning their elements cannot be changed
or modified after creation.
- Once a tuple is defined, you cannot add, remove, or modify
elements.

3. Mixed Data Types:


- Tuples can contain elements of different data types.
- You can mix integers, floats, strings, and other types within the
same tuple.
mixed_tuple = (1, 'two', 3.0, [4, 5])

4. Accessing Elements:
- Elements in a tuple are accessed using indexing (starting from 0).

5. Length:
- The `len()` function returns the number of elements in a tuple.

Use Cases:
1. Coordinates:
2. RGB Color Values:
3. Employee Information:
4. Geographical Data:
5. Stock Data:

Tuple method:
Tuples in Python have two built-in methods: count() and index().

1. count() method:

The `count()` method returns the number of occurrences of a


specified element in the tuple.

Syntax:

[Link](element)
2. index() method:

The `index()` method returns the index of the first occurrence of a


specified element in the tuple.

Syntax:
[Link](element[, start[, end]])

element: The element to search for in the tuple.


start (optional): The index from which the search begins. Default is 0.
end (optional): The index at which the search ends. Default is the
end of the tuple.

Note: If the specified element is not found in the tuple, both `count()`
and `index()` methods will raise a `ValueError`. To avoid this, you can
check the presence of an element using the `in` operator before using
these methods.

Set:

In Python, a set is an unordered and mutable collection of unique


elements.

1. Unordered: The elements in a set do not have a specific order.


Unlike lists, you cannot access elements by index in a set.

2. Mutable: You can add and remove elements from a set. This allows
you to modify the content of a set after its creation.
3. Unique Elements: A set does not allow duplicate elements. If you
try to add an element that already exists in the set, it won't be added
again.

4. Syntax: Sets are defined using curly braces `{}` or the `set()`
constructor. For example:

my_set = {1, 2, 3, 4, 5}

5. Creating an Empty Set: An empty set can be created using `set()`:

empty_set = set()

6. Common Operations: Sets support various operations inspired by


mathematical set theory, including union, intersection, difference,
and symmetric difference.

7. Use Cases: Sets are useful when dealing with collections of unique
elements, such as removing duplicates from a list, checking for
membership, or performing set operations.

Sets are particularly useful in scenarios where you need to work with
unique elements and perform set operations efficiently.
Set operations:

Some common set operations.

1. Union (| or `union()`):
The union of two sets includes all unique elements from both sets.

2. Intersection (& or `intersection()`):


The intersection of two sets includes only the common elements
between them.

2.1 intersection_update():
intersection_update() method is different from the intersection()
method, because the intersection() method returns a new set,
without the unwanted items, and the intersection_update()
method removes the unwanted items from the original set.

3. Difference (- or `difference()`):
The difference of two sets includes elements that are in the first set
but not in the second.

3.1 difference_update():
difference_update() method is different from the difference() method,
because the difference() method returns a new set, without the
unwanted items, and the difference_update() method removes
the unwanted items from the original set.

4. Symmetric Difference (^ or `symmetric_difference()`):


The symmetric difference of two sets includes elements that are in
either of the sets, but not in both.
4.1 symmetric_difference_update():
The symmetric_difference_update() method updates the original set
by removing items that are present in both sets, and inserting the
other items.

Subset and Superset Concept:

subset:-
For two sets A and B, if every element in set A is present in set B,
then set A is a subset of set B(A ⊆ B) and B is the superset of
set A(B ⊇ A).

Example: A = {1,2,3} B = {1,2,3,4,5,6}

A ⊆ B, since all the elements in set A are present in set B.

Superset:-
In set theory, a superset is the opposite concept of a subset. If set (A)
contains every element of set (B), and possibly more elements,
then (A) is considered a superset of (B).

For example, continuing with the previous example:

[ A = {1, 2, 3, 4, 5} ]
[ B = {1, 2, 3} ]

Here, (A) is a superset of (B) because every element in (B) (1, 2, 3) is


also present in (A), and (A) has additional elements (4, 5). This
relationship is denoted as (A is a superset of B).
5. Subset (`issubset()`):
Check if one set is a subset of another.

6. Superset (`issuperset()`):
Check if one set is a superset of another.

7. Disjoint Sets:
Two sets are disjoint sets if there are no common elements in both
sets.
Example: A = {1,2,3,4} B = {7,8,9,10}. Here, set A and set B are
disjoint sets.

Adding and Removing Elements:

1. add(element):
The add() method adds a single element to the set.
If the element already exists, the add() method does not add the
element.

2. update(iterable):
Adds multiple elements from an iterable (list, tuple, set, etc.) to the
set.

3. remove(element):
Removes the specified element from the set. Raises an error if the
element is not present.

4. discard(element):
Removes the specified element from the set if it is present. Does
not raise an error if the element is not found.
5. pop():
The pop() method removes and returns a random item from the
set. Raises an error if the set is empty.

Copy and Clear method:

Copy():
The copy() method copies the set.

clear():
The clear() method removes all elements in a set.

Dictionary:

A dictionary in Python is an ordered collection of key-value pairs.


Each key must be unique, and it is associated with a corresponding
value. Dictionaries are created using curly braces {} or the dict()
constructor.

Rules for defining a dictionaries:

1. Enclosure with Curly Braces (`{}`):


Dictionaries are defined using ‘curly braces’.
Each key-value pair is separated by a colon ‘:’
Syntax:
{key1: value1, key2: value2, ...}
2. Keys are Unique:
Every key in a dictionary must be unique. If you try to assign a value
to an existing key, it will overwrite the previous value associated
with that key.

3. Keys are Immutable:


Keys must be of an immutable data type (e.g., strings, numbers, or
tuples). Lists and other dictionaries are not allowed as keys.

4. Key-Value Pairs:
Dictionaries consist of key-value pairs separated by a colon (`:`). Each
key is followed by its corresponding value.

5. Order (Python 3.7 and later):


Starting from Python 3.7, dictionaries maintain the order in which
items were inserted. This means that when you iterate over the
dictionary, the order of items will be preserved.

6. Accessing Values:
Values in a dictionary are accessed using their corresponding keys.

print(my_dict['name'])

7. Mutable:
Dictionaries are mutable, meaning you can modify, add, or remove
key-value pairs after the dictionary is created.
Dictionaries Method:

[Link]():
The clear() method removes all items from a dictionary. After using
clear(), the dictionary becomes empty.

Syntax:
my_dict.clear()

[Link]():
The copy() method in Python is used to create a shallow copy of a
dictionary. A shallow copy means that a new dictionary is created, but
the keys and values inside the new dictionary are references to the
same objects as the keys and values in the original dictionary.

Syntax:
copied_dict = original_dict.copy()

[Link]():
The fromkeys() method creates a new dictionary with keys from a
given iterable and values set to a default value.
Here, iterable is the iterable (list, tuple, etc.) from which keys will be
taken, and value is the default value to be set for all keys. If value
is not provided, it defaults to None.

Syntax:
[Link](iterable, value)
[Link]():
The get() method retrieves the value associated with a specified
key. It provides a way to safely access dictionary elements without
raising a KeyError if the key is not present.

Syntax:
[Link](key, default)

●​ key: The key to look up in the dictionary.


●​ default: The value to return if the key is not found. If not
specified, the default value is None.

[Link]():
The items() method returns a view of the dictionary's key-value pairs
as tuples. Each tuple contains a pair of the key and its
corresponding value.
This view object can be converted to a list or used in various
iterations.

[Link]():
The keys() method displays a list of all the keys in a dictionary.
Syntax:
keys_view = my_dict.keys()

[Link]():
The values() method displays a list of all the values in a dictionary.
Syntax:
keys_view = my_dict.values()
[Link]():
The pop() method removes and returns the value associated with a
specified key from a dictionary. If the key is not found, it raises a
KeyError or returns a specified default value if provided.

syntax:
pop(key, default=None):
●​ key: The key whose associated value is to be removed and
returned.
●​ default (optional): If the key is not found, the method returns this
value. If not provided and the key is not found, a KeyError is
raised

[Link]():
The popitem() method removes and returns the last key-value pair
from the dictionary as a tuple.
Syntax:
removed_item = my_dict.popitem()

[Link]():
setdefault() method gets the value of a key from a dictionary. If the
key is present in the dictionary, it returns the corresponding value. If
the key is not present, it inserts the key with a specified default
value and returns that value.

syntax:
[Link](key, default_value)

●​ key: The key to be searched in the dictionary.


●​ default_value: The value to be inserted for the key if the key is
not present in the dictionary.
[Link]():
The update() method inserts the specified items to the dictionary.
The specified items can be a dictionary, or an iterable object with key
value pairs.
If a key already exists in the original dictionary, its value is
updated; otherwise, a new key-value pair is added.
Syntax:
[Link]({key:value})

List Comprehension:
List comprehension is a concise way to create lists in Python. It
allows you to create a new list by specifying the elements you
want to include, often in a single line of code. List comprehensions
are both expressive and efficient, making your code more readable
and concise.
Syntax:
new_list = [expression for item in iterable if condition]

●​ expression: The expression to be evaluated and included in the


new list.
●​ item: The variable representing each item in the iterable.
●​ iterable: The sequence (e.g., list, tuple, string, etc.) to iterate
over.
●​ condition (optional): An optional condition that filters elements
based on a specified criterion.

Nested If statement:
Syntax:
new_list = [expression for item in iterable if condition1 if condition2 ...]
If else statement:
Syntax:
new_list = [result_if_true if condition else result_if_false for item in
iterable]

Nested For loop Statement:


Syntax:
new_list = [expression for outer_item in outer_iterable for inner_item
in inner_iterable if condition]

Higher order Function:


Higher-order functions in Python are functions that take one or
more functions as arguments or return a function as a result.

[Link]():
The map() function in Python is a built-in function that applies a
specified function to all items in an iterable (such as a list, tuple,
or string) and returns an iterator that produces the results. It
provides a concise way to perform operations on each element of
a collection without the need for explicit loops.

Syntax:
map(function, tierable, ...)

function: The function to apply to each item in the iterable.


iterable: One or more iterables (e.g., lists, tuples) whose elements will
be processed by the function.
Note:
●​ The `map()` function returns an iterator, so you often need to
convert it to a list or another iterable type to see the results.
●​ map() can accept multiple iterable arguments. In this case,
the provided function must take as many arguments as there are
iterables.
●​ The function provided to `map()` can be a built-in function, a
user-defined function, or a lambda function.

[Link]():
The `filter()` function in Python is a built-in function used for filtering
elements of an iterable (e.g., a list) based on a specified function
called a "predicate." The `filter()` function returns an iterator
containing the elements from the iterable for which the predicate
returns `True`.

Syntax:
filter(function, iterable)

function: A function that tests whether each element of an iterable


should be included in the result. If `None`, it simply returns the
elements of the iterable that are true.
iterable: The iterable (e.g., list, tuple, string, etc.) whose elements are
tested by the function.

[Link]():
The `reduce()` function in Python is part of the `functools` module
and is used to successively apply a function (a function taking two
arguments) to the items of an iterable, reducing it to a single
cumulative result. It's particularly useful for operations like computing
the sum of elements, finding the maximum value, or any other
cumulative operation like sum()`, `max()`, or `min()`

Syntax:
[Link](function, iterable)

function: The function to apply. It should take two arguments.


iterable: The iterable (e.g., list, tuple, etc.) whose elements will be
successively combined.
Understanding call by value vs call by reference is key to avoiding
bugs and weird behavior in Python and other languages.

Concept Meaning
Call by A copy of the variable is passed to the function. The
Value original is unchanged.
Call by The actual variable's reference is passed, so
Reference changes inside the function affect the original.

“Mutable objects behave like call by reference,​


while immutable objects behave like call by value.”

Example 1: Immutable (int, str, tuple = Call by Value-like)


def modify(x):
x=x+5
print("Inside function:", x)

num = 10
modify(num)
print("Outside function:", num)

Output:
Inside function: 15
Outside function: 10

➡️ The value of num didn’t change outside. (Because int is


immutable)

📌 Example 2: Mutable (list, dict = Call by Reference-like)


def modify_list(my_list):
my_list.append(100)
print("Inside function:", my_list)

nums = [1, 2, 3]
modify_list(nums)
print("Outside function:", nums)

Output:
Inside function: [1, 2, 3, 100]
Outside function: [1, 2, 3, 100]

➡️ The list was modified both inside and outside the function.
🧠 Summary
Data Type Behavior in Function
int, float, str, Call by value-like
tuple (immutable)
list, dict, set Call by reference-like
(mutable)

Want to try a small quiz to test it? Or do you want a real-world


example like working with a shopping cart or database records?

You might also like