Class Attributes: Class attributes are shared among all instances of a class. They are defined within the class but outside any methods using the class
keyword. They have the same value for every instance of the class.
pythonclass MyClass:
class_attribute = 10
obj1 = MyClass()
obj2 = MyClass()
print(obj1.class_attribute) # Output: 10
print(obj2.class_attribute) # Output: 10
Instance Attributes: Instance attributes are specific to each instance of a class. They are defined within the class's methods using the self
keyword and have different values for each instance.
pythonclass MyClass:
def __init__(self, value):
self.instance_attribute = value
obj1 = MyClass(5)
obj2 = MyClass(7)
print(obj1.instance_attribute) # Output: 5
print(obj2.instance_attribute) # Output: 7
2. Remove duplicate items from a list in Python
To remove duplicate items from a list, you can convert the list into a set to automatically eliminate duplicates and then convert it back to a list.
pythonmy_list = [1, 2, 2, 3, 4, 4, 5]
unique_list = list(set(my_list))
print(unique_list) # Output: [1, 2, 3, 4, 5]
3. Remove items from a list in Python
To remove specific items from a list, you can use the remove()
method.
pythonmy_list = [1, 2, 3, 4, 5]
my_list.remove(3)
print(my_list) # Output: [1, 2, 4, 5]
4. repr() vs str() in Python
repr()
returns a printable representation of an object, which can be used to recreate the object. str()
, on the other hand, returns a human-readable string representation of an object.
pythonclass MyClass:
def __repr__(self):
return "MyClass()"
def __str__(self):
return "Instance of MyClass"
obj = MyClass()
print(repr(obj)) # Output: MyClass()
print(str(obj)) # Output: Instance of MyClass
5. How to sort a dictionary by value in Python?
You can use the sorted()
function along with a lambda function as the key
parameter to sort the dictionary by its values.
pythonmy_dict = {'apple': 5, 'banana': 2, 'orange': 8}
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))
print(sorted_dict) # Output: {'banana': 2, 'apple': 5, 'orange': 8}
6. globals() and locals() Method in Python
globals()
returns a dictionary representing the global symbol table, and locals()
returns a dictionary representing the current local symbol table.
pythonglobal_var = 10
def my_function():
local_var = 20
print(globals()) # Output: {'__name__': '__main__', 'global_var': 10, ...}
print(locals()) # Output: {'local_var': 20}
my_function()
7. Convert User Input to a Number
You can use the input()
function to get user input, and then use type casting to convert it to a specific numeric type like int or float.
pythonuser_input = input("Enter a number: ")
number = int(user_input)
print(number) # Output: (User input as an integer)
8. Convert String to Datetime in Python
You can use the strptime()
method from the datetime
module to convert a string to a datetime object.
pythonfrom datetime import datetime
date_string = "2023-07-30"
date_object = datetime.strptime(date_string, "%Y-%m-%d")
Introduction:
In Python, you can call external commands using the subprocess
module. This module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.
Code Example:
pythonimport subprocess
# Example command: ls (list files in the current directory)
command = "ls"
# Run the command and capture the output
result = subprocess.run(command, shell=True, capture_output=True, text=True)
# Print the output
print(result.stdout)
Explanation:
- We import the
subprocess
module to use its functionalities for calling external commands. - In this example, we call the "ls" command using
subprocess.run()
. - The
shell=True
parameter allows us to use shell features, andcapture_output=True
captures the command's output. - The
text=True
parameter converts the output to a string for easier handling. - The result is then printed using
print(result.stdout)
.
Topic 10: How to Count the Occurrences of a List Item?
Introduction:
To count the occurrences of a specific item in a list, you can use the count()
method.
Code Example:
python# Example list
my_list = [1, 2, 2, 3, 4, 2, 5]
# Count occurrences of '2'
count_of_2 = my_list.count(2)
# Print the count
print("Count of 2:", count_of_2)
Explanation:
- We have a list called
my_list
containing various elements, including multiple occurrences of '2'. - Using the
count()
method, we find the number of occurrences of '2' and store it in the variablecount_of_2
. - The count is then printed using
print()
.
Topic 11: How to Flatten List in Python?
Introduction:
Flattening a nested list means converting it into a single-dimensional list. You can achieve this using various approaches, like using list comprehension or the itertools.chain()
method.
Code Example:
python# Example nested list
nested_list = [[1, 2], [3, 4], [5, 6]]
# Method 1: Using list comprehension
flattened_list = [item for sublist in nested_list for item in sublist]
# Method 2: Using itertools.chain()
import itertools
flattened_list2 = list(itertools.chain(*nested_list))
# Print the flattened lists
print("Flattened list (Method 1):", flattened_list)
print("Flattened list (Method 2):", flattened_list2)
Explanation:
- We start with a nested list called
nested_list
. - Method 1: We use list comprehension to iterate through each sublist and each item within the sublists, creating a single list
flattened_list
. - Method 2: We import the
itertools
module and use thechain()
method to combine the sublists into a single iterable. We convert the iterable into a list to getflattened_list2
. - Both flattened lists are then printed using
print()
.
Topic 12: How to Merge Dictionaries in Python?
Introduction:
In Python, you can merge dictionaries using the update()
method or dictionary unpacking (Python 3.5+).
Code Example:
python# Example dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
# Method 1: Using update() method
merged_dict1 = dict1.copy()
merged_dict1.update(dict2)
# Method 2: Using dictionary unpacking (Python 3.5+)
merged_dict2 = {**dict1, **dict2}
# Print the merged dictionaries
print("Merged dictionary (Method 1):", merged_dict1)
print("Merged dictionary (Method 2):", merged_dict2)
Explanation:
- We have two dictionaries,
dict1
anddict2
, containing key-value pairs. - Method 1: We create a copy of
dict1
and use theupdate()
method to mergedict2
intomerged_dict1
. - Method 2: We use dictionary unpacking (
{**dict1, **dict2}
) to merge the dictionaries and createmerged_dict2
. - Both merged dictionaries are then printed using
print()
.
Topic 13: How to Pass Value by Reference in Python?
Introduction:
In Python, objects are passed to functions by reference by default. This means that when you pass an object (e.g., list or dictionary) to a function and modify it inside the function, the changes are reflected outside the function as well.
Code Example:
pythondef modify_list(my_list):
my_list.append(4)
# Example list
original_list = [1, 2, 3]
# Call the function with the list
modify_list(original_list)
# Print the modified list
print("Modified list:", original_list)
Explanation:
- We define a function
modify_list()
that takes a list as an argument and appends '4' to it. - We have an example list called
original_list
. - When we call the
modify_list()
function withoriginal_list
, the list is modified inside the function. - After the function call, we print
original_list
and see that it has been modified.
Topic 14: Compare Strings in Python
Introduction:
You can compare strings in Python using comparison operators like ==
, !=
, <
, >
, <=
, and >=
. These operators perform lexicographic (dictionary) comparisons based on the ASCII values of characters.
Code Example:
python# Example strings
string1 = "apple"
string2 = "banana"
# Compare strings using comparison operators
is_equal = string1 == string2
is_not_equal = string1 != string2
is_less_than = string1 < string2
is_greater_than = string1 > string2
# Print the comparison results
print("Equal:", is_equal)
print("Not Equal:", is_not_equal)
print("Less Than:", is_less_than)
print("Greater Than:", is_greater_than)
Explanation:
- We have two example strings,
string1
andstring2
. - We use various comparison operators to compare the strings and store the results in different variables.
- The comparison results are then printed using
print()
.
Topic 15: Convert File Data to List
Introduction:
To convert data from a file into a list in Python, you can open the file, read its content, and split it into individual elements to create a list.
Code Example:
Suppose we have a file named "data.txt" with the following content:
apple
banana
orange
python# Read data from the file and convert to list
with open("data.txt", "r") as file:
data_list = file.read().splitlines()
# Print the list
print("Data List:", data_list)
Explanation:
- We open the file "data.txt" in read mode using the
open()
function and use awith
block to ensure the file is properly closed after reading. - We read the file content using
file.read()
and split it into lines using.splitlines()
, creatingdata_list
. - The list is then printed using
print()
. The output will show the list containing the lines from the file as its elements.
0 Comments