(1) How Are Arguments Passed By Value Or By Reference In python?
- Pass by value: A copy of the actual object is passed. Changing the value of the copy of the object will not change the value of the original object.
- Pass by reference: Reference to the actual object is passed. Changing the value of the new object will change the value of the original object.
- In Python, arguments are passed by reference, i.e., reference to the actual object is passed.
Example-1:
def appendNumber(array):
array.append(4)
arr = [1, 2, 3] # Mutable Object
print(arr)
appendNumber(arr)
print(arr)
[1, 2, 3]
[1, 2, 3, 4]
Note:
- Here, ‘arr’ is passed as a ‘reference’, hence if we change the value, the original value will also get changed.
Example-2:
def appendString(name):
last_name = "Sahoo"
name = name + last_name
name = "Subrat" # Immutable Object
print(name)
appendString(name)
print(name)
Subrat
Subrat
Note:
- Here, also ‘name’ is passed as a ‘reference’, but as the string is an immutable type, if we change the value, the original one will not get affected.
(2) What Are Iterators In Python?
- In Python, an iterator is an object that allows you to iterate over collections of data, such as lists, tuples, dictionaries, and sets.
- If your iteration process requires going through the values or items in a data collection one item at a time, then you’ll need another piece to complete the puzzle. You’ll need an iterator.
Iterators take responsibility for two main actions:
- Returning the data from a stream or container one item at a time.
- Keeping track of the current and visited items.
What Is the Python Iterator Protocol?
- A Python object is considered an iterator when it implements two special methods collectively known as the iterator protocol.
- These two methods make Python iterators work.
- So, if you want to create custom iterator classes, then you must implement the following methods:
- __iter__(): The iter() method is called for the initialization of an iterator. This returns an iterator object
- __next__(): The next method returns the next value for the iterable. When we use a for loop to traverse any iterable object, internally it uses the iter() method to get an iterator object, which further uses the next() method to iterate over. This method raises a StopIteration to signal the end of the iteration.
Example-1: Iterating Using next() Method
string = "Subrat"
ch_iterator = iter(string)
print(next(ch_iterator))
print(next(ch_iterator))
print(next(ch_iterator))
print(next(ch_iterator))
print(next(ch_iterator))
print(next(ch_iterator))
print(next(ch_iterator))
S
u
b
r
a
t
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
Input In [66], in <cell line: 10>()
8 print(next(ch_iterator))
9 print(next(ch_iterator))
---> 10 print(next(ch_iterator))
StopIteration:
Example-2: Iterating Using for() Loop
my_list = [1, 2, 3, 4, 5]
iterator = iter(my_list)
for element in iterator:
print(element)
1
2
3
4
5
Example-3: Building Custom Iterators
- Building an iterator from scratch is easy in Python. We just have to implement the
__iter__()
and the__next__()
methods,
__iter__()
returns the iterator object itself. If required, some initialization can be performed.__next__()
must return the next item in the sequence. On reaching the end, and in subsequent calls, it must raiseStopIteration
.
class SequenceIterator:
def __init__(self, sequence):
self._sequence = sequence
self._index = 0
def __iter__(self):
return self
def __next__(self):
if self._index < len(self._sequence):
item = self._sequence[self._index]
self._index += 1
return item
else:
raise StopIteration
for item in SequenceIterator([1, 2, 3, 4]):
print(item)
1
2
3
4
(3) Explain How To Delete A File In Python?
- Use command os.remove(file_name)
Example:
import os
os.remove("ChangedFile.csv")
print("File Removed!")
File Removed
(4) Explain split() and join() Functions In Python?
- You can use split() function to split a string based on a delimiter to a list of strings.
- You can use join() function to join a list of strings based on a delimiter to give a single string.
Example:
string = "This is a string."
string_list = string.split(' ')
print(string_list)
print(' '.join(string_list))
['This', 'is', 'a', 'string.']
This is a string.
(5) What Does *args And **kwargs Mean?
*args:
- *args in function definitions in Python is used to pass a variable number of arguments to a function.
- It is used to pass a non-keyworded, variable-length argument list.
Example:
def names(name1, name2, *args):
print(name1)
print(name2)
for name in args:
print(name)
names('Subrat','Arpita','Subhada','Sonali','Abhispa')
Subrat
Arpita
Subhada
Sonali
Abhispa
**kwargs:
- “**kwargs” KeyWord Argument is used to accept the variable length, key, and value pair argument lists.
- A keyworded argument means a variable that has a name when passed to a function.
Example:
def students(school, **kwargs):
print('School Name: ', school)
for key, value in kwargs.items():
print(f'{key} : {value}')
students('DPS', Name = "Subrat", Roll_No = '120' , Mark = 98)
School Name: DPS
Name : Subrat
Roll_No : 120
Mark : 98