Python_Practical_Explained
Python_Practical_Explained
---
### Code:
```python
def sum_list(lst):
return sum(lst)
# Example
sample_list = [1, 2, 3, 4]
print("Sum of list:", sum_list(sample_list))
```
### Explanation:
- The `sum()` function returns the total sum of all elements in the list.
- Here, 1+2+3+4 = 10
### Output:
```
Sum of list: 10
```
---
### Code:
```python
def multiply_list(lst):
result = 1
for num in lst:
result *= num
return result
### Explanation:
- Initialize a variable `result` with 1.
- Multiply each number in the list with `result`.
### Output:
```
Product of list: 24
```
---
### Code:
```python
def max_in_list(lst):
return max(lst)
print("Max of list:", max_in_list(sample_list))
```
### Explanation:
- The built-in function `max()` returns the largest item.
### Output:
```
Max of list: 4
```
---
### Code:
```python
def min_in_list(lst):
return min(lst)
### Explanation:
- The built-in function `min()` returns the smallest item.
### Output:
```
Min of list: 1
```
---
## 5. Count strings where length >= 2 and first and last char are same
### Code:
```python
def count_special_strings(lst):
return sum(1 for s in lst if len(s) >= 2 and s[0] == s[-1])
### Explanation:
- The condition checks two things:
1. Length is at least 2.
2. First and last characters are the same.
### Output:
```
Count of special strings: 3
```
---
### Code:
```python
def sort_by_last(tuples):
return sorted(tuples, key=lambda x: x[-1])
sample_tuples = [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
print("Sorted by last element:", sort_by_last(sample_tuples))
```
### Explanation:
- Use `sorted()` with a key that targets the last element of each tuple using `x[-
1]`.
### Output:
```
Sorted by last element: [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]
```
---
### Code:
```python
def remove_duplicates(lst):
return list(set(lst))
### Explanation:
- A `set` stores only unique elements. Converting a list to a set removes
duplicates.
- Then we convert it back to a list.
### Output:
```
List without duplicates: ['1221', 'xyz', 'aba']
```
---
### Code:
```python
def is_empty(lst):
return len(lst) == 0
### Explanation:
- Check if the length of list is 0.
### Output:
```
Is list empty (sample_list): False
```
---
### Code:
```python
def clone_list(lst):
return lst[:]
### Explanation:
- `lst[:]` creates a copy of the list using slicing.
### Output:
```
Cloned list: [1, 2, 3, 4]
```
---
### Code:
```python
def words_longer_than_n(words, n):
return [word for word in words if len(word) > n]
### Explanation:
- This uses list comprehension to filter out words longer than `n`.
### Output:
```
Words longer than 3: ['hello', 'computer', 'python']
```
---