This Is Your Complete Guide To All Python List Methods
Tags: python, programming, beginners, codenewbie
Published: 2021-07-31 23:32:31

Hi, I'm [Aya Bouchiha](https://t.me/AyaBouchiha), today, I'm going to talk about the list of built-in objects.

## Definition of a List

A list is a mutable, iterable,  ordered collection of values. It is used to store different and multiple values in one variable.

## Creating a list

```python
new_list = ['hi', 1, False, {"name":"Aya"}, [10, 20], None]

print(new_list) # ['hi', 1, False, {"name":"Aya"}, [10, 20], None]
print(type(new_list)) # <class 'list'>
print(len(new_list)) # 6
```

# All list methods

## append()

**append(value)**: this list method lets you insert an element at the end of the list.

```python
my_list = [10, 20, 30]

my_list.append(40)

print(my_list.append(50)) # None

print(my_list) # [10, 20, 30, 40, 50]

my_list.append() # error
```

## insert()

**insert(index, value)**: used to add a new element at a given index

```python
admins = ['Aya Bouchiha', 'John Doe']

admins.insert(0, 'Simon Bihao') 
print(admins)  # ['Simon Bihao', 'Aya Bouchiha', 'John Doe']

admins.insert(2, 'Salma Nouhary')
print(admins) # ['Simon Bihao', 'Aya Bouchiha', 'Salma Nouhary', 'John Doe']
```

## pop()

**pop(index = -1)**: delete the elements that exist in the given index, by default the index is the `-1` which is the index of the last element. In addition, it returns the deleted element.

```python
admins = ['Aya Bouchiha', 'John Doe']
old_admin = admins.pop()

print(old_admin) # John Doe
print(admins) # ['Aya Bouchiha']


tasks = ['eat fruits', 'go to gym', 'drink water']
completed_task = tasks.pop(1)

print(completed_task) # go to gym
print(tasks) # ['eat fruits', 'drink water']
```

## remove()

**remove(value)**: deletes the first item that matches the given value.

```python
tasks = ['eat fruits', 'go to gym', 'drink water']
tasks.remove('eat fruits')

print(tasks.remove('drink water')) # None
print(tasks) # ['go to gym']
tasks.remove('something else') # error
```

## clear()

**clear()**: used to remove all list's items.

```python
tasks = ['eat fruits', 'go to gym', 'drink water']

print(len(tasks)) # 3

tasks.clear()

print(tasks) # []
print(len(tasks)) # 0
```

## copy()

**copy()**: this list method is used to return a copy of the specified list.

```python
today_tasks = ['eat fruits', 'go to gym', 'drink water']

tomorrow_tasks = today_tasks.copy()

print(tomorrow_tasks) #  ['eat fruits', 'go to gym', 'drink water']

today_tasks.clear()

print(today_tasks) # []

print(tomorrow_tasks) # ['eat fruits', 'go to gym', 'drink water']
```

## index()

**index(value)**: returns the index of the first item that matched the given value.

```python
today_tasks = ['eat fruits', 'go to gym', 'drink water']

print(today_tasks.index('eat fruits')) # 0
print(today_tasks.index('drink water')) # 2
print(today_tasks.index('buy a mouse')) # error
```

## count()

**count(value)**: returns the number of repeated items that match the specified value in a list.

```python
product_prices = [12, 227, 0, 54, 0, 20]
free_products_number = product_prices.count(0)

print(free_products_number) # 2
print(product_prices.count(224578)) # 0
```

## extend()

**extend(iterable)**: helps you to insert an iterable(list, set,...) at the end of the specified list.

```python
all_users = ['Yasm', 'Nopay', 'Houssam']
facebook_users = {'Aya', 'Simon'}
instagram_users = ('Ayman', 'Soha')

all_users.extend(facebook_users)
all_users.extend(instagram_users)

# ['Yasm', 'Nopay', 'Houssam', 'Simon', 'Aya', 'Ayman', 'Soha']
print(all_users)
```

## reverse()

**reverse()**: reverse the order of the specified list

```python
marks = [15, 45, 51, 70]
marks.reverse()

print(marks) # [70, 51, 45, 15]
```

## sort()

**sort(reverse = False, key(optional))**: sort the list's items, if the reverse parameter was True, the items will be sorted in descending order.

the key parameter is used to specify a function that will specify the sorting criteria.

*Example:1*
```python
marks = [7, 62, 71, 56, 24]
marks.sort()

print(marks) # [7, 24, 56, 62, 71]

marks.sort(reverse=True)

print(marks) # [71, 62, 56, 24, 7]

```
*Example:2*
```python
def get_marks(student: dict):
  return student.get('marks')
  
students = [
  {
    "name": "Aya Bouchiha",
    "email": "developer.aya.b@gmail.com",
    "marks": 92
  },
  {
    "name": "John Doe",
    "email": "john.doe@gmail.com",
    "marks": 95
  },
  {
    "name": "Ryan Hosm",
    "email": "ryan.hosm@gmail.com",
    "marks": 80
  }
]

students.sort(key=get_marks)

print(students)
# [{'name': 'Ryan Hosm', 'email': 'ryan.hosm@gmail.com', 'marks': 80}, {'name': 'Aya Bouchiha', 'email': 'developer.aya.b@gmail.com', 'marks': 92}, {'name': 'John Doe', 'email': 'john.doe@gmail.com', 'marks': 95}]

```

*Example3 (**using lambda**)*

```python
products = [
  {
    "name" : "laptop",
    "price": 500
  },
  {
    "name" : "phone",
    "price": 150
  },
  {
    "name" : "mouse",
    "price": 16
  },
  {
    "name": "keyboard",
    "price": 24
  }
  
]

products.sort(reverse=True, key=lambda product: product.get("price"))
print(products)

highest_price = products[0].get('price')
print(f'highest price is: {highest_price}')
```

*Output:*
```python
[{'name': 'laptop', 'price': 500}, {'name': 'phone', 'price': 150}, {'name': 'keyboard', 'price': 24}, {'name': 'mouse', 'price': 16}]
highest price is: 500
```


### Summary

+ **append(value)**: inserts an element at the end of the list.

+ **insert(index, value)**: adds a new element at a given index.

+ **pop(index = -1)**: deletes the element that exist in the given index.

+ **remove(value)**: deletes the first item that match the given value.

+ **clear()**: removes all list's items.

+ **copy()**: returns a copy of the specified list.

+ **index(value)**: returns the index of the first item that matched the given value.

+ **count(value)**: returns the number of repeated items that match the specified value in a list.

+ **extend(iterable)**: inserts an iterable at the end of the specified list.

+ **reverse()**: reverses the order of the specified list.

+ **sort(reverse = False, key(optional))**: sorts the list's items.


### References & useful Resources

+ [https://www.w3schools.com/python/python_lists.asp](https://www.w3schools.com/python/python_lists.asp)

+ [https://www.programiz.com/python-programming/methods/list](https://www.programiz.com/python-programming/methods/list)

+ [https://docs.python.org/3/tutorial/datastructures.html](https://docs.python.org/3/tutorial/datastructures.html)

+ [https://www.youtube.com/watch?v=9OeznAkyQz4](https://www.youtube.com/watch?v=9OeznAkyQz4)

+ [https://www.youtube.com/watch?v=rrGmQbmTfiA](https://www.youtube.com/watch?v=rrGmQbmTfiA)

## Suggested posts

+ [All You Need To Know About Python JSON Module](https://dev.to/ayabouchiha/all-you-need-to-know-about-python-json-module-5ef0)

+ [5 Helpful Python Random Module Methods](https://dev.to/ayabouchiha/5-helpful-python-math-module-methods-44gf)

+ [5 Helpful Python Math Module Methods](https://dev.to/ayabouchiha/5-helpful-python-math-module-methods-44gf)

+ [5 Useful Python String Methods](https://dev.to/ayabouchiha/5-useful-python-string-methods-4pe7)


To Contact Me:

email:developer.aya.b@gmail.com
telegram: [Aya Bouchiha](https://t.me/AyaBouchiha)

Hope you enjoyed reading this post :)