Professional Documents
Culture Documents
List in Python
List in Python
# List slicing
print("\nList Slicing:")
subset_of_fruits = fruits[1:4]
print("Subset of Fruits:", subset_of_fruits)
```python
fruits = ["apple", "banana", "orange", "grape"]
```
```python
print(fruits[0]) # Output: "apple"
print(fruits[-1]) # Output: "grape"
```
```python
fruits[1] = "pear"
```
```python
removed_fruit = fruits.pop(2)
```
```python
subset_of_fruits = fruits[1:3]
```
```python
length_of_list = len(fruits)
```
```python
if "kiwi" in fruits:
print("Kiwi is in the list.")
```
```python
fruits.insert(1, "peach")
```
```python
for fruit in fruits:
print(fruit)
```
#### 12. **List Comprehension:**
- List comprehensions provide a concise way to create lists.
- Example:
```python
squared_numbers = [x**2 for x in range(5)]
```
```python
new_list = fruits.copy()
```
```python
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
```
*********