DEV Community 👩‍💻👨‍💻

Cover image for 5 Of The Most Helpful Python List Methods
Aya Bouchiha
Aya Bouchiha

Posted on

5 Of The Most Helpful Python List Methods

Hello everybody,
Today we'll discuss 5 helpful Python list methods.

clear()

clear(): This method helps you to delete all list elements.

cities = ['azemmour', 'tanger', 'casablanca']
print(len(cities)) # 3
cities.clear()
print(cities) # []
print(len(cities)) # 0
Enter fullscreen mode Exit fullscreen mode

reverse()

reverse(): reverse the order of the list's elements.

cities = ['azemmour', 'tanger', 'casablanca']
cities.reverse()

print(cities)  # ['casablanca', 'tanger', 'azemmour']
Enter fullscreen mode Exit fullscreen mode

copy()

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

cities = ['azemmour', 'tanger', 'casablanca']
moroccan_cities = cities.copy()
cities[0] = 'madrid'

print(cities) # ['madrid', 'tanger', 'casablanca']
print(moroccan_cities) # ['azemmour', 'tanger', 'casablanca']
Enter fullscreen mode Exit fullscreen mode

count(value)

count(): returns the number of repeated items with the given value in a specified 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
Enter fullscreen mode Exit fullscreen mode

index(value)

index(value): this list method returns the position at the first occurrence of the given value in the specified list.in addition, this method raises an error if the given value does not exist in the specified list.

admins = ['John Doe', 'Aya Bouchiha', 'Simon Heebo']

print(admins.index('Aya Bouchiha')) # 1
print(admins.index('this is not an admin')) # error
Enter fullscreen mode Exit fullscreen mode

summary

  • clear(): deletes all list's elements.
  • reverse(): reverse the order of the list's elements.
  • copy(): returns a copy of the specified list.
  • count(value): returns the number of repeated items with the given value in a specified list.
  • index(value): returns the position at the first occurrence of the given value in the specified list, and raises an error if the given value is not found.

References & useful Resources

To Contact Me:

Have a great day!

Top comments (0)

🌚 Turn on dark mode

🔠 Change your default font

📚 Adjust your experience level to see more relevant content

 

Head to your account's Settings to do all this and more.