Q 1 . What is Lambda function?
Ans: A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression
x = lambda a, b : a * b print(x(5, 6))
Q 2. What is __init__?
Ans: __init__ is a constructor method in Python and is automatically called to allocate memory when a new object/instance is created. All classes have a __init__ method associated with them
# class definition class Student: def __init__(self, fname, lname, age, section): self.firstname = fname self.lastname = lname self.age = age self.section = section # creating a new object stu1 = Student("Sara", "Ansh", 22, "A2")
Q 3. What is slicing in Python?
Ans:
- As the name suggests, ‘slicing’ is taking parts.
- Syntax for slicing is [start : stop : step]
- start is the starting index from were to slice a list or tuple
- stop is the ending index or where to sop.
- a step is the number of steps to jump.
- The default value for start is 0, stop is a number of items, and step is 1.
- Slicing can be done on strings, arrays, lists, and tuples.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(numbers[1 : : 2]) #output : [2, 4, 6, 8, 10]
Q 4. What is the difference between Python Arrays and lists?
Ans:
- Arrays in python can only contain elements of the same data types i.e., the data type of the array should be homogeneous. It is a thin wrapper around C language arrays and consumes far less memory than lists.
- Lists in python can contain elements of different data types i.e., the data type of lists can be heterogeneous. It has the disadvantage of consuming large memory.
import array a = array.array('i', [1, 2, 3]) for i in a: print(i, end=' ') #OUTPUT: 1 2 3 a = array.array('i', [1, 2, 'string']) #OUTPUT: TypeError: an integer is required (got type str) a = [1, 2, 'string'] for i in a: print(i, end=' ') #OUTPUT: 1 2 string
Q 5. What is the use of self in Python?
Ans: Self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments. self is used in different places and is often thought to be a keyword. But unlike in C++, self is not a keyword in Python.
Q.6 What are Built-in Data Types in Python?
Ans:
- Number -
- List - [5,"Market","2.4"]
- Tuple -(3, 'tool',1)
- String -
- Set - {7,6,8}
- Dictionary -{1:"apply", 2:"mango"}
- Boolean -True or False
- Array -[1,2,3]