In Python, the term "array" is often used interchangeably with "list." Lists are a versatile and widely used data structure in Python. Here's an explanation with examples:
1. Creating Lists (Arrays):
```python
numbers = [1, 2, 3, 4, 5]
words = ['apple', 'banana', 'orange']
mixed_types = [1, 'hello', 3.14, True]
```
Lists can contain elements of different types, and you can create them by enclosing elements in square brackets.
2. Accessing Elements:
```python
numbers = [1, 2, 3, 4, 5]
first_element = numbers[0]
last_element = numbers[-1]
print(first_element, last_element)
```
You can access elements using index notation. Negative indices count from the end of the list.
3. Slicing:
```python
numbers = [1, 2, 3, 4, 5]
subset = numbers[1:4]
print(subset)
```
Slicing allows you to extract a portion of the list. In this example, it gets elements at indices 1, 2, and 3.
4. Modifying Lists:
```python
numbers = [1, 2, 3, 4, 5]
numbers[2] = 9
numbers.append(6)
numbers.extend([7, 8])
print(numbers)
```
Lists are mutable, meaning you can modify them by assigning new values, appending, or extending.
5. List Comprehension:
```python
squares = [x**2 for x in range(1, 6)]
print(squares)
```
List comprehensions provide a concise way to create lists. In this example, it creates a list of squares from 1 to 5.
6. List Functions:
```python
numbers = [3, 1, 4, 1, 5, 9, 2]
sorted_numbers = sorted(numbers)
length = len(numbers)
total = sum(numbers)
```
The `sorted()` function sorts a list, `len()` returns the length, and `sum()` calculates the sum of the elements.
7. Multidimensional Lists (Nested Lists):
```python
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[1][2])
```
Lists can contain other lists, creating a multidimensional structure. In this example, it's a 3x3 matrix.
Lists in Python are fundamental data structures and are used extensively in various applications due to their flexibility and ease of use.
0 Comments