Long Python
Long Python
For Loop:
A for loop iterates over a sequence (like a
list, string, or range) and executes a block of
code for each element in that sequence.
Example: for i in range(5):
print(i)
Explanation:
The loop runs 5 times, with i taking
values from 0 to 4.
It automatically stops after completing
the range of values.
Conclusion:
Use while loop when you need a loop
to continue until a condition changes.
Use for loop when you know the
number of iterations in advance or
want to iterate through a collection.
about:blank 1/9
10/24/24, 11:16 PM 00000
How many operators are
available in python? Explain all
with suitable examples.
In Python, there are 7 categories of
operators that are used to perform different
types of operations on values and variables.
These are:
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
1. Arithmetic Operators
These operators are used to perform
mathematical operations like addition,
subtraction, etc.
Operator Description Example
+ 5 + 3 =
Addition 8
5 - 3 =
- Subtraction 2
* Multiplication 515* 3 =
5 / 3 =
/ Division 1.666...
%
Modulus 5 % 3 =
(Remainder) 2
5 ** 3 =
** Exponentiation 125
// Floor Division 5 // 3 =
1
2. Comparison (Relational)
Operators
These operators are used to compare two
values. The result is either True or False.
Operator Description Example
== 5 == 3
Equal to (False)
!= Not equal to 5 != 3
(True)
> Greater than 5 > 3 (True)
5 < 3
< Less than (False)
>=
Greater than or 5 >= 3
equal to (True)
<= Less than or equal to 5(False)
<= 3
3. Assignment Operators
These operators are used to assign values to
variables.
Operator Description Example
= Assigns value x = 5
x += 3 (x = x +
+= Adds and assigns 3)
-=
Subtracts and x -= 3 (x = x -
assigns 3)
*=
Multiplies and x *= 3 (x = x *
assigns 3)
/= Divides and x /= 3 (x = x /
assigns 3)
%= Modulus and x %= 3 (x = x %
assigns 3)
**= Exponent and x **= 3 (x = x
assigns ** 3)
//= Floor divide and x //= 3 (x = x
assigns // 3)
4. Logical Operators
These operators are used to perform logical
operations, returning either True or False.
Operator Description Example
and True if both are (5 > 3) and (5
True < 8) (True)
or True if at least (5 > 3) or (5
one is True > 8) (True)
not Inverts the not(5 > 3)
result (False)
5. Bitwise Operators
These operators work with binary numbers
(bit-level operations).
Operator Description Example
& Bitwise AND 5 & 3 = 1
` ` Bitwise OR
^ Bitwise XOR 5 ^ 3 = 6
~ Bitwise NOT ~5 = -6
<< Left Shift 5 << 1 = 10
>> Right Shift 5 >> 1 = 2
6. Membership Operators
These operators are used to test whether a
value is a member of a sequence like strings,
lists, or tuples.
Operator Description Example
True if value is 'a' in
in found in the 'apple'
sequence (True)
True if value is not 'b' not in
not in found in the 'apple'
sequence (True)
7. Identity Operators
These operators are used to compare objects,
to check if they are the same object in
memory.
Operator Description Example
is
True if both variables x is y
point to the same object
True if both variables x is not
is not point to different
objects y
about:blank 2/9
10/24/24, 11:16 PM 00000
Conclusion:
Python provides a variety of operators to
perform different operations. Understanding
these operators allows developers to
manipulate data and control the flow of logic
in programs effectively.
Key Points:
Interactive mode is more suitable for
small code snippets and learning.
Script mode is used for writing full
programs and storing them for future
use.
2. Identity Operator:
The identity operators (is, is not) are used
to compare if two variables refer to the same
object in memory, not just if their values are
equal.
Example:
a = [1, 2, 3] b = [1, 2, 3] c = a
print(a is b) # False (a and b have
the same value but are different
objects) print(a is c) # True (a and
c refer to the same object) print(b
is not c) # True (b and c are
different objects)
3. Escape Sequence:
Escape sequences are used to insert special
characters in a string. They are preceded by a
backslash (\) and represent characters that
have special meanings (like newline, tab,
etc.).
Example:
print("Hello\nWorld") # Prints on two
lines print("He said, \"Python is
great!\"") # Prints quotes inside a
string
about:blank 3/9
10/24/24, 11:16 PM 00000
\n is the escape sequence for a new
line.
\" allows double quotes inside a
string.
4. Slicing:
Slicing is used to extract a portion of a
sequence (like a list, tuple, or string) by
specifying a range of indices. It is done using
the colon (:) operator.
Example:
my_list = [10, 20, 30, 40, 50]
print(my_list[1:4]) # Output: [20,
30, 40] print(my_list[:3]) # Output:
[10, 20, 30] print(my_list[2:]) #
Output: [30, 40, 50]
Summary:
Membership Operator checks for
presence (in, not in).
Identity Operator checks if variables
point to the same object (is, is not).
Escape Sequence allows special
characters in strings (e.g., \n for new
line).
Slicing extracts specific parts of
sequences like lists or strings (e.g.,
list[start:end]).
2. swapcase():
The swapcase() function returns a new string
where all the uppercase characters are
converted to lowercase and all lowercase
characters are converted to uppercase.
Example:
text = "Hello, World!" result =
text.swapcase() print(result) #
"hELLO, wORLD!"
3. isspace():
The isspace() function checks whether all
the characters in a string are whitespace
characters. If all characters are whitespaces
(spaces, tabs, newlines), it returns True;
otherwise, it returns False.
Example:
text1 = " " text2 = "Hello"
print(text1.isspace()) # True
print(text2.isspace()) # False
Summary:
lstrip() removes leading spaces
from a string.
swapcase() swaps the case of all
letters (lowercase to uppercase and
vice versa).
isspace() checks if a string contains
only whitespace characters.
about:blank 4/9
10/24/24, 11:16 PM 00000
my_dict = dict(name="Alice",
age=25) print(my_dict)
Note that keys do not need
quotes when using this
method.
3. Creating an Empty Dictionary: You can
create an empty dictionary and add
key-value pairs later.
Example:
my_dict = {} my_dict["name"] =
"Alice" my_dict["age"] = 25
print(my_dict)
4. Using dict() with a List of Tuples:
You can create a dictionary from a list
of tuples, where each tuple represents
a key-value pair.
Example:
my_dict = dict([("name",
"Alice"), ("age", 25)])
print(my_dict)
5. Using Dictionary Comprehension:
Dictionary comprehension allows you
to create a dictionary in a compact
way, often from an iterable like a list
or range.
Example:
Summary:
A dictionary stores key-value pairs,
allowing fast lookups by key.
Ways to create a dictionary include:
Using curly braces {}.
Using the dict() constructor.
Starting with an empty
dictionary and adding pairs.
Using a list of tuples.
Using dictionary
comprehension.
2. insert():
The insert() method inserts an element at
a specified position in the list. It takes two
arguments: the index at which to insert the
element and the element itself.
Example:
my_list = [1, 2, 3, 4]
my_list.insert(2, "new")
print(my_list) # Output: [1, 2,
'new', 3, 4]
3. remove():
about:blank 5/9
10/24/24, 11:16 PM 00000
The remove() method removes the first
occurrence of the specified element from the
list. If the element is not found, it raises a
ValueError.
Example:
my_list = [1, 2, 3, 4, 3]
my_list.remove(3) print(my_list) #
Output: [1, 2, 4, 3]
4. pop():
The pop() method removes and returns the
element at the specified index. If no index is
provided, it removes and returns the last
element of the list.
Example:
my_list = [1, 2, 3, 4] element =
my_list.pop(2) print(my_list) #
Output: [1, 2, 4] print(element) #
Output: 3
Summary:
reverse(): Reverses the list in place.
insert(): Inserts an element at a
specified index.
remove(): Removes the first
occurrence of the specified element.
pop(): Removes and returns the
element at a specified index, or the
last element if no index is provided.
1. Mutable Objects:
Definition: Mutable objects can have
their values changed after they are
created. You can modify the content of
a mutable object in place.
Examples: Lists, dictionaries, sets, and
byte arrays are mutable.
Example of Mutable Object:
my_list = [1, 2, 3] my_list[0] = 10 #
Modifying the first element
print(my_list) # Output: [10, 2, 3]
2. Immutable Objects:
Definition: Immutable objects cannot
have their values changed after they
are created. If you try to modify an
immutable object, Python creates a
new object instead.
Examples: Strings, tuples, integers,
floats, and frozensets are immutable.
Example of Immutable Object:
my_tuple = (1, 2, 3) # my_tuple[0] =
10 # This would raise an error since
tuples are immutable new_tuple = (10,
2, 3) # Create a new tuple with the
modified value print(new_tuple) #
Output: (10, 2, 3)
Key Differences:
Aspect Mutable Immutable
Objects Objects
Can be Cannot be
Modification modified after modified once
creation. created.
Lists, Strings,
Example dictionaries, tuples,
Types sets. integers,
floats.
Modifications New memory
Memory happen in place is allocated
Allocation (same memory for any
address). changes.
Generally Faster for
slower for read-only
Performance frequent
updates due to operations, as
in-place no changes
changes. are allowed.
Strings:
my_string =
my_list[0] = "Hello" +
Example of 10 (modifies list
Mutation in place). "World"
(creates a
new string).
Conclusion:
Mutable objects like lists and
dictionaries can be modified in place
without changing their identity.
about:blank 6/9
10/24/24, 11:16 PM 00000
Immutable objects like strings and
tuples cannot be changed once
created; any "modification" results in a
new object being created.
Key Points:
Tuples are immutable, meaning their
elements cannot be changed after
creation.
Elements can be accessed using
indexing and slicing.
Tuples are often used when you want
to store a collection of items that
should not change.
6. update()
The update() method updates the dictionary
with elements from another dictionary or
from an iterable of key-value pairs. Existing
keys will have their values updated, while
new keys will be added.
Example:
my_dict = {"name": "Alice", "age":
25} my_dict.update({"age": 26,
"city": "New York"}) print(my_dict) #
Output: {'name': 'Alice', 'age': 26,
'city': 'New York'}
7. get()
The get() method returns the value for a
specified key if it exists in the dictionary. If the
key does not exist, it returns None or a
specified default value.
Example:
value = my_dict.get("name")
print(value) # Output: Alice #
Example with a non-existent key
value_not_exist =
my_dict.get("country", "Not Found")
print(value_not_exist) # Output: Not
Found
Summary of Dictionary
Methods:
Method Description Example
Returns a
keys()
view of all my_dict.keys()
keys in the
dictionary.
Returns a
view of all
values() values in my_dict.values()
the
dictionary.
Returns a
items()
view of all my_dict.items()
key-value
pairs.
Removes
clear()
all items my_dict.clear()
from the
dictionary.
Returns a
shallow
copy() copy of the my_dict.copy()
dictionary.
Updates
the
update()
dictionary my_dict.update({"key":
with key- "value"})
value
pairs.
Returns
the value my_dict.get("key",
get() for a
specified default_value)
key.
These methods provide essential
functionalities for managing and interacting
with dictionaries in Python, making them a
powerful tool for handling key-value data.
about:blank 8/9
10/24/24, 11:16 PM 00000
print("List after removing
duplicates:", unique_numbers)
Explanation:
1. Create a List: We first define a list
called numbers that contains 10
numbers, including duplicates.
2. Print Original List: We display the
original list to show its contents
before removing duplicates.
3. Remove Duplicates:
We convert the list to a set
using set(numbers), which
removes any duplicate values
because sets only store unique
items.
We then convert the set back
to a list using list().
4. Print Unique List: Finally, we print the
new list, which contains only unique
numbers.
Sample Output:
Original list: [10, 20, 30, 10, 40,
50, 20, 60, 70, 80] List after
removing duplicates: [40, 10, 50, 20,
70, 80, 30, 60]
about:blank 9/9