Lists in Python and its methods
Tags: programming, python
Published: 2023-05-11 06:51:49

Lists are mutable ordered and indexed collections of objects.
We can change, add, or remove items in a list after it has been created. Items can be of any data type, such as numbers, strings, or other objects. 
Lists are formed by placing a comma-separated list of expressions in square brackets.

```python
my_list = ["Hello", "World", 1, 2]
```

## Accessing list items

We can access the items in a list by using their index values, which start from 0 for the first item. We can also use negative indexes to access the items from the end of the list. 

For example:

```python
print(my_list[0]) # prints "Hello"
print(my_list[-1]) # prints 2
```

## Nested lists

We can also add lists within another list.

```python
my_list = [ [0, 1, 3], ['a', 'b', 'c'], ['red', 'yellow', 'blue'] ]
print(new_list[2][1]) # prints yellow
```

## Slicing of a List

Using slicing, we can print a specific range of elements from a list. The python list ‘Slice’ operation is used to print a specific range of elements; it is denoted by the ‘Colon (:)’.  To print the elements from a specific range, use the start index tag (:index) to specify the last range element until which we want to specify (index:).

```python
my_list = ['A', 'E', 'I', 'O', 'U']
print(my_list[1:4]) # prints ['E', 'I', 'O']
```

## Looping through a list

We can loop through a list using the 'in' keyword:

```python
my_list = ['red', 'blue', 'green', 'black']

for thing in my_list:
    print(thing)
```

## List concatenation

We can join multiple lists using '+' operator:

```python
a = [0, 1, 2, 3, 4]
b = [5, 6, 7, 8, 9]
c = a + b
print(c) # prints [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
```

## Multiple concatenation

We can return a sequence self-concatenated specified amount of times using '*' operator:

```python
a = [0, 1]
b = a * 3
print(b) # prints [0, 1, 0, 1, 0, 1]
```

## List Comprehension

A list comprehension consists of an expression followed by the for statement inside square brackets.

```python
numbers = [n*n for n in range(1, 6)]
print(numbers) # prints [1, 4, 9, 16, 25]
```

## Using Lists as Stacks

The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index. For example:

```python
stack = [3, 4, 5]
stack.append(6)
stack.append(7)
print(stack) # prints [3, 4, 5, 6, 7]

stack.pop() # 7
stack.pop() # 6
stack.pop() # 5
print(stack) # prints[3, 4]
```

## List methods

* ### len(list)

    It gives the overall length of the list.

    ```python
    my_list = ['A', 'E', 'I', 'O', 'U']
    print(len(my_list)) # prints 5
    ```

* ### append()

    Adds one element to the end of the list.

    ```python
    my_list = ['A', 'E', 'I', 'O']
    my_list.append('U')
    print(my_list) # prints ['A', 'E', 'I', 'O', 'U']
    ```

* ### insert()

    Adds a component at the required position.

    ```python
    my_list = ['A', 'E', 'I', 'O']
    my_list.insert(2,'U')
    print(my_list) # prints ['A', 'E', 'U', 'I', 'O']
    ```

* ### extend()

    Adds multiple elements to a list from another list.

    ```python
    a=[1,2]
    b=[3,4]
    a.extend(b)
    print(a) # prints [1, 2, 3, 4]
    ```

* ### pop()

    Removes the element at the required position.

    ```python
    my_list = ['A', 'E', 'I', 'O', 'U']
    my_list.pop(2)
    print(my_list) # prints ['A', 'E', 'O', 'U']
    ```

    Without any argument passed, it will remove element from the end of the list

    ```python
    my_list = ['A', 'E', 'I', 'O', 'U']
    my_list.pop()
    print(my_list) # prints ['A', 'E', 'I', 'O']
    ```

* ### remove()
    
    Remove the first item from the list whose value is equal to given argument. 
    It raises a ValueError if there is no such item.

    ```python
    my_list = ['A', 'E', 'I', 'O', 'U']
    my_list.remove('I')
    print(my_list) # prints ['A', 'E', 'O', 'U']
    ```

* ### del()

    We can also use the del statement to remove one or more items from a list.

    ```python
    a = [3, 2, 3, 8, 3, 4, 5, 6, 1, 2]
    
    del a[1] # deleting the second item
    print(a) # prints [3, 3, 8, 3, 4, 5, 6, 1, 2]
    
    del a[-1] # deleting the last item
    print(a) # [3, 3, 8, 3, 4, 5, 6, 1]

    del a[0 : 2] # delete first two items
    print(a) # prints # [8, 3, 4, 5, 6, 1]
    ```
    
* ### sort()

    Sorts the list in ascending order.

    ```python
    my_list = [8, 1, 5, 3, 7]
    my_list.sort()
    print(my_list) # prints [1, 3, 5, 7, 8]
    ```

    To sort descending order:

    ```python
    my_list = [8, 1, 5, 3, 7]
    my_list.sort(reverse = True)
    print(my_list) # prints [8, 7, 5, 3, 1]
    ```

* ### reverse()

    Reverses the order of the list.

    ```python
    my_list = ['A', 'E', 'I', 'O', 'U']
    my_list.reverse()
    print(my_list) # prints ['U', 'O', 'I', 'E', 'A']
    ```

* ### index()

    Returns the first appearance of a particular value.
    It raises a ValueError if there is no such item.

    ```python
    my_list = ['A', 'E', 'I', 'O', 'U']
    print(my_list.index('O')) # prints 3
    ```

* ### count()

    Returns the number of elements with the required value.

    ```python
    my_list = [3, 4, 4, 1, 2, 3, 8, 3]
    print(my_list.count(4)) # prints 2
    print(my_list.count(3)) # prints 3
    ```

* ### max(list)

    It returns an item from the list with a max value.

    ```python
    a = [3, 2, 3, 8, 3]
    print(max(a)) # prints 8
    ```

* ### min(list)

    It returns an item from the list with a min value.

    ```python
    a = [3, 2, 3, 8, 3]
    print(min(a)) # prints 2
    ```
* ### copy()
    
    Returns a duplicate (Shallow Copy) of the list.

    ```python
    a = [3, 2, 3, 8, 3]
    b=a.copy()
    print(b) # print [3, 2, 3, 8, 3]
    ```

    We can also copy (Deep Copy) using '=':

    ```python
    a = [3, 2, 3, 8, 3]
    b=a
    print(b) # prints [3, 2, 3, 8, 3]
    a.pop()
    print(b) # prints [3, 2, 3, 8]
    ```
    
* ### clear()

    Removes all the elements from the list.

    ```python
    a = [3, 2, 3, 8, 3]
    a.clear()
    print(a) # prints []
    ```

## Reference

* https://python-reference.readthedocs.io/en/latest/docs/list/
* https://python-adv-web-apps.readthedocs.io/en/latest/lists.html
* https://docs.python.org/3/tutorial/datastructures.html
* https://www.programiz.com/python-programming/list