Python 2nd Internal
Python 2nd Internal
Gaurishankar":
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)
```
- **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.
Python provides several built-in string methods that allow you to manipulate and analyze strings. Here are a few common
string methods:
**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! "]
```
**Example**:
```python
import re
In this example, `findall()` finds all occurrences of the substring "in" in the given text.
**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'
```
### 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]