Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 28, 2021 11:40 pm GMT

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)) # 3cities.clear()print(cities) # []print(len(cities)) # 0

reverse()

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

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

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']

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) # 2print(product_prices.count(224578)) # 0

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')) # 1print(admins.index('this is not an admin')) # error

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!


Original Link: https://dev.to/ayabouchiha/5-of-the-most-helpful-python-list-methods-2c31

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To