This Is Your Complete Guide To All Python List Methods

Hi, I'm Aya Bouchiha, 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

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.

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

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.

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.

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.

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.

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.

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.

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.

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

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

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

def get_marks(student: dict):
  return student.get('marks')

students = [
  {
    "name": "Aya Bouchiha",
    "email": "[email protected]",
    "marks": 92
  },
  {
    "name": "John Doe",
    "email": "[email protected]",
    "marks": 95
  },
  {
    "name": "Ryan Hosm",
    "email": "[email protected]",
    "marks": 80
  }
]

students.sort(key=get_marks)

print(students)
# [{'name': 'Ryan Hosm', 'email': '[email protected]', 'marks': 80}, {'name': 'Aya Bouchiha', 'email': '[email protected]', 'marks': 92}, {'name': 'John Doe', 'email': '[email protected]', 'marks': 95}]

Example3 (using lambda)

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:

[{'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

Suggested posts

To Contact Me:

Hope you enjoyed reading this post :)

13