Here are the answers to your questions based on the concepts typically covered in programming books like "SS
Gaurishankar":
1. Define List with an Example:
A list is a mutable, ordered collection of items in Python. Lists can contain elements of different data types.
Example:
my_list = [1, 2, 3, 'apple', 4.5]
2. Define Dictionary with an Example:
A dictionary is an unordered collection of key-value pairs in Python. Each key must be unique, and it is used to access the
corresponding value.
Example:
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
3. Define len() with List Example:
The `len()` function returns the number of items in an object, such as a list.
Example:
my_list = [1, 2, 3, 4]
length = len(my_list) # length will be 4
4. Define del Statement with Example:
The `del` statement is used to delete an object or a variable in Python.
Example:
my_list = [1, 2, 3, 4]
del my_list[1] # my_list will now be [1, 3, 4]
5. Define setdefault() with Example:
The `setdefault()` method in dictionaries returns the value of a specified key. If the key does not exist, it inserts the key with
a specified value.
Example:
my_dict = {'name': 'Alice'}
value = my_dict.setdefault('age', 25) # my_dict is now {'name': 'Alice', 'age': 25}
6. Define upper(), islower() String Methods with Example:
- `upper()`: Converts all characters in a string to uppercase.
- `islower()`: Checks if all characters in a string are lowercase.
Example:
my_string = "hello"
upper_string = my_string.upper() # upper_string will be "HELLO"
is_lower = my_string.islower() # is_lower will be True
7. Define in and not in Operator with Dictionary Example:
The `in` operator checks if a key exists in a dictionary, while `not in` checks if a key does not exist.
Example:
my_dict = {'name': 'Alice', 'age': 25}
exists = 'name' in my_dict # exists will be True
not_exists = 'city' not in my_dict # not_exists will be True
8. Write Steps to Use Regular Expression in Python:
1. Import the `re` module.
2. Compile a regular expression pattern using `re.compile()`.
3. Use methods like `search()`, `match()`, or `findall()` to search for patterns in strings.
4. Use the results as needed.
9. What is re.compile() and re.search() Method:
re.compile()`: Compiles a regular expression pattern into a regex object, which can be used for matching.
`re.search()`: Searches the string for a match to the compiled regex pattern and returns a match object if found;
otherwise, it returns `None`.
example:
import re
pattern = re.compile(r'\d+') # Compiles a pattern to match digits
match = pattern.search('There are 123 apples') # Searches for digits in the string
05 MARKS:
Here are the detailed answers to your questions, suitable for a 5-mark response:
### 1. What is Tuple Datatype? Explain with Example and Differences from a List.
A **tuple** is an immutable, ordered collection of items in Python. Tuples can contain elements of different data types,
similar to lists, but once a tuple is created, its elements cannot be modified, added, or removed.
**Example**:
```python
my_tuple = (1, 2, 3, 'apple', 4.5)
```
**Differences between Tuple and List**:
- **Mutability**:
- Tuples are immutable (cannot be changed).
- Lists are mutable (can be changed).
- **Syntax**:
- Tuples are defined using parentheses `()`.
- Lists are defined using square brackets `[]`.
- **Performance**:
- Tuples can be slightly faster than lists for iteration due to their immutability.
- **Use Cases**:
- Tuples are often used for fixed collections of items, while lists are used for collections that may change.
### 2. Explain String Methods with Example Code.
Python provides several built-in string methods that allow you to manipulate and analyze strings. Here are a few common
string methods:
- **`upper()`**: Converts all characters to uppercase.
- **`lower()`**: Converts all characters to lowercase.
- **`strip()`**: Removes leading and trailing whitespace.
- **`replace(old, new)`**: Replaces occurrences of a substring with another substring.
- **`split(separator)`**: Splits a string into a list based on a separator.
**Example Code**:
```python
my_string = " Hello, World! "
print(my_string.upper()) # Output: " HELLO, WORLD! "
print(my_string.lower()) # Output: " hello, world! "
print(my_string.strip()) # Output: "Hello, World!"
print(my_string.replace("World", "Python")) # Output: " Hello, Python! "
print(my_string.split(",")) # Output: [" Hello", " World! "]
```
### 3. Explain `findall()` Method with Respect to Regular Expression.
The `findall()` method in the `re` module returns all non-overlapping matches of a pattern in a string as a list. If no matches
are found, it returns an empty list.
**Example**:
```python
import re
text = "The rain in Spain falls mainly in the plain."
pattern = r'in'
matches = re.findall(pattern, text)
print(matches) # Output: ['in', 'in', 'in']
```
In this example, `findall()` finds all occurrences of the substring "in" in the given text.
### 4. Write the Following:
**a) The Difference Between List and Dictionary with Example**:
- **List**: An ordered collection of items that can be accessed by their index.
- **Dictionary**: An unordered collection of key-value pairs where each key is unique.
**Example**:
```python
# List
my_list = ['apple', 'banana', 'cherry']
print(my_list[1]) # Output: 'banana'
# Dictionary
my_dict = {'name': 'Alice', 'age': 25}
print(my_dict['name']) # Output: 'Alice'
```
**b) Write the Output of the Following Statements**:
```python
spam = ['cat', 'bat', 'rat', 'elephant']
```
1) `spam[2]` → Output: `'rat'`
2) `spam[10]` → Output: `IndexError: list index out of range`
3) `spam[-2]` → Output: `'rat'`
4) `spam[1:3]` → Output: `['bat', 'rat']`
5) `spam[0:]` → Output: `['cat', 'bat', 'rat', 'elephant']`
### 5. Explain the Sorting Values in a List Using `sort()` Method with Examples.
The `sort()` method is used to sort the elements of a list in place (i.e., it modifies the original list). By default, it sorts in
ascending order. You can also specify the `reverse` parameter to sort in descending order.
**Example**:
```python
my_list = [5, 2, 9, 1, 5, 6]
my_list.sort() # Sorts in ascending order
print(my_list) # Output: [1, 2, 5, 5, 6, 9]
my_list.sort(reverse=True) # Sorts in descending order
print(my_list) # Output: [9, 6, 5, 5, 2, 1]
``
10 MARKS: