Home  >  Article  >  Backend Development  >  A Quick Guide to Python List Methods with Examples

A Quick Guide to Python List Methods with Examples

WBOY
WBOYOriginal
2024-09-12 10:16:30344browse

A Quick Guide to Python List Methods with Examples

Introduction

Python lists are versatile and come with a variety of built-in methods that help in manipulating and processing data efficiently. Below is a quick reference to all the major list methods along with brief examples.

1. append(item)

Adds an item to the end of the list.

lst = [1, 2, 3]
lst.append(4)  # [1, 2, 3, 4]

2. clear()

Removes all items from the list.

lst = [1, 2, 3]
lst.clear()  # []

3. copy()

Returns a shallow copy of the list.

lst = [1, 2, 3]
new_lst = lst.copy()  # [1, 2, 3]

4. count(item)

Counts the occurrences of an item.

lst = [1, 2, 2, 3]
lst.count(2)  # 2

5. extend(iterable)

Extends the list by appending all elements from the iterable.

lst = [1, 2, 3]
lst.extend([4, 5])  # [1, 2, 3, 4, 5]

6. index(item, start, end)

Returns the index of the first occurrence of an item.

lst = [1, 2, 3]
lst.index(2)  # 1

7. insert(index, item)

Inserts an item at the specified index.

lst = [1, 2, 3]
lst.insert(1, 'a')  # [1, 'a', 2, 3]

8. pop(index)

Removes and returns the item at the specified index (default is the last item).

lst = [1, 2, 3]
lst.pop()  # 3, lst = [1, 2]

9. remove(item)

Removes the first occurrence of an item.

lst = [1, 2, 3]
lst.remove(2)  # [1, 3]

10. reverse()

Reverses the items in the list in place.

lst = [1, 2, 3]
lst.reverse()  # [3, 2, 1]

11. sort(key, reverse)

Sorts the list in place (ascending by default).

lst = [3, 1, 2]
lst.sort()  # [1, 2, 3]
lst.sort(reverse=True)  # [3, 2, 1]

12. sorted()

Returns a new sorted list from the items in an iterable.

lst = [3, 1, 2]
sorted(lst)  # [1, 2, 3]

13. len(list)

Returns the number of items in a list.

lst = [1, 2, 3]
len(lst)  # 3

14. max(list)

Returns the largest item in a list.

lst = [1, 2, 3]
max(lst)  # 3

15. min(list)

Returns the smallest item in a list.

lst = [1, 2, 3]
min(lst)  # 1

16. sum(list)

Returns the sum of all items in a list.

lst = [1, 2, 3]
sum(lst)  # 6

17. list()

Creates a list from an iterable.

s = "abc"
lst = list(s)  # ['a', 'b', 'c']

Conclusion

These list methods cover the core functionalities you will need while working with lists in Python. Whether it’s appending items, sorting, or making shallow copies, these methods allow you to manipulate data efficiently.

The above is the detailed content of A Quick Guide to Python List Methods with Examples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn