Python Lists

0

Creating Lists

A list in Python can be created by placing a sequence of values (items) separated by commas within square brackets:

```python
my_list = [1, 2, 3, 4, 5]
```

Lists can contain items of different data types, although it is typical for all items to be of the same type:

```python
mixed_list = [1, "two", 3.0, True]
```

Indexing and Slicing

Like strings and other built-in sequence types, lists can be indexed and sliced. Indexing refers to accessing an element of the list by its position, starting with 0 for the first element:

```python
first_element = my_list[0]  # Returns 1
```

Slicing allows you to obtain a sublist by specifying a start and end index (end index not included):

```python
sublist = my_list[1:3]  # Returns [2, 3]
```

All slice operations return a new list containing the requested elements, which means that the following slice returns a shallow copy of the list:

```python
copy_of_list = my_list[:]
```

List Operations

Lists support a variety of operations, such as concatenation using the `+` operator:

```python
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2  # Returns [1, 2, 3, 4, 5, 6]
```

Unlike strings, which are immutable, lists are mutable. This means you can change their content. For example, you can modify an element of the list directly:

```python
my_list[2] = "three"
```

Adding and Removing Elements

You can add new items to the end of the list using the `append()` method:

```python
my_list.append(6)  # my_list becomes [1, 2, "three", 4, 5, 6]
```

Assignment to slices is also possible, allowing changes in size of the list or even clearing it entirely:

```python
my_list[1:3] = ["a", "b", "c"]  # my_list becomes [1, "a", "b", "c", 4, 5, 6]
my_list[:] = []  # Clears the list, making it empty
```

The built-in function `len()` can be used to get the number of items in a list:

```python
length = len(my_list)  # Returns 7, if my_list was not cleared
```

Nested Lists

Lists can also be nested, meaning you can create lists that contain other lists:

```python
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
```

You can access elements of the nested lists using multiple indices:

```python
element = nested_list[1][2]  # Returns 6
```
Tags

Post a Comment

0Comments
Post a Comment (0)