In Python, a list is a versatile and mutable data structure that can store a collection of items. Here are some examples illustrating the use of lists:
1. Creating Lists:
```python
numbers = [1, 2, 3, 4, 5]
fruits = ['apple', 'banana', 'orange']
mixed_list = [1, 'hello', 3.14, True]
```
2. Accessing Elements:
```python
my_list = ['a', 'b', 'c', 'd']
first_element = my_list[0] # 'a'
last_element = my_list[-1] # 'd'
```
3. Slicing Lists:
```python
numbers = [1, 2, 3, 4, 5]
subset = numbers[1:4] # [2, 3, 4]
```
4. Modifying Lists:
```python
fruits = ['apple', 'banana', 'orange']
fruits[1] = 'grape' # Modifying an element
fruits.append('kiwi') # Appending an element
fruits.extend(['melon', 'berry']) # Extending the list
```
5. Removing Elements:
```python
numbers = [1, 2, 3, 4, 5]
del numbers[2] # Removing an element by index
popped_value = numbers.pop() # Removing and returning the last element
```
6. List Methods:
```python
numbers = [4, 2, 8, 1, 6]
numbers.sort() # Sorting the list
reversed_numbers = sorted(numbers, reverse=True) # Sorting in reverse order
```
7. Nested Lists:
```python
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
element = matrix[1][2] # Accessing a nested element
```
These examples showcase the basic operations and concepts related to lists in Python. Lists are widely used due to their flexibility and ability to store different types of data.
0 Comments