11 Python List Methods That You Must Know

From this article, you will learn how to add elements to, alter, and delete elements from Python lists.

One of the first built-in data structures you’ll learn about when you begin programming in Python is lists. In the following few minutes, we’ll go over the fundamentals of Python lists before going over a number of helpful list methods you may employ when working with lists.

Let’s get started!

Introduction to Python Lists

A list in Python is a grouping of objects of the same or distinct data types. Using looping structures like for loops, you may iterate across the collection to get the elements.

Lists adhere to zero indexing and provide slicing operations, much as all Python iterables.

Since they are changeable collections, you may make changes to them as you go. This encompasses a variety of operations, such as adding and deleting items from the list, sorting the items in a certain order, flipping the components’ positions, and more. You may carry out these operations using Python’s built-in list functions.

Let’s now examine a few practical Python list techniques.

Python’s built-in list methods

Some useful list methods will be covered in this section. To demonstrate these list methods in action, we’ll use code samples.

The following pgm_langs list will be used. The names of well-known programming languages are contained in a list of strings.

pgm_langs = ['Python','Go','Rust','JavaScript']

With insert(), add list items

At a specific index, you could wish to insert an element. Use the insert() function to do this. Following information is included in the call to the insert() list method:

The index at which the element should be added;

The element to insert

Using the index() technique, let’s add « Scala » at position 1.

pgm_langs = ['Python','Go','Rust','JavaScript']
pgm_langs.insert(1,'Scala')
print(pgm_langs)
# Output: ['Python', 'Scala', 'Go', 'Rust', 'JavaScript']

Insert Item into List Using append()

You might occasionally need to extend the list by adding an element. The add() function may be used to do this.

Let’s use the append() function to insert the text « Java » to the end of the list.

pgm_langs.append('Java')
print(pgm_langs)
# Output: ['Python', 'Scala', 'Go', 'Rust', 'JavaScript', 'Java']

Include an Iterable using extend()

You are aware that adding a single item is possible using the append() technique. But what if you wanted to include many things in an already-existing list, like a list of items? A clear syntax is provided via the extend() function.

Let’s use the extend() function to add the items from the list more_langs to the pgm_langs list.

more_langs = ['C++','C#','C']
pgm_langs.extend(more_langs)
print(pgm_langs)
# Output: ['Python', 'Scala', 'Go', 'Rust', 'JavaScript', 'Java', 'C++', 'C#', 'C']

The append() function may be used to add each item one at a time by iterating through the list of items. This is verbose, though. Additionally, using the extend() approach is more practical.

for lang in more_langs:
    pgm_langs.append(lang)

List Reversal Using reverse()

You may use the reverse() function to change the order of the entries in a list.

The pgm_langs list is inverted, as can be seen.

pgm_langs.reverse()
print(pgm_langs)
# Output: ['C', 'C#', 'C++', 'Java', 'JavaScript', 'Rust', 'Go', 'Scala', 'Python']

List Sorting Using sort()

Using the sort() function, you may sort a Python list while it is open. We can see that the sorting is done alphabetically because pgm_langs is a list of strings.

pgm_langs.sort()
print(pgm_langs)
# Output: ['C', 'C#', 'C++', 'Go', 'Java', 'JavaScript', 'Python', 'Rust', 'Scala']

By setting the reverse option to True in the sort() method call, the list may be sorted in reverse alphabetical order.

pgm_langs.sort(reverse=True)
print(pgm_langs)
# Output: ['Scala', 'Rust', 'Python', 'JavaScript', 'Java', 'Go', 'C++', 'C#', 'C']

Copy Shallowly Using the copy() Method

Sometimes it may be preferable to alter a replica of the original list as opposed to the original list itself. A shallow copy of the Python list is what the list function copy() produces.

Call it pgm_langs_copy and let’s make a shallow copy of the pgm_langs list. We then print out the list with « Haskell » as the first member.

pgm_langs_copy = pgm_langs.copy()
pgm_langs_copy[0]='Haskell'
print(pgm_langs_copy)
# Output: ['Haskell', 'Rust', 'Python', 'JavaScript', 'Java', 'Go', 'C++', 'C#', 'C']

We can see that the pgm_langs list has not been altered, though. As a result, altering a shallow duplicate but leaving the original unchanged does not change the list.

print(pgm_langs)
# Output: ['Scala', 'Rust', 'Python', 'JavaScript', 'Java', 'Go', 'C++', 'C#', 'C']

Use count() for item count

Sometimes knowing how frequently an element appears in a list is useful. The count() function gives the quantity of occurrences of each element in a list.

All components in the pgm_langs list only appear once. So, when we attempt to calculate the number of « Go, » we obtain 1, which is accurate.

print(pgm_langs.count('Go'))
# Output: 1

One option for clearing out duplicate items from Python lists is to use the count() function.

With index(), obtain an item’s index

The index() function in Python may be used to determine an item’s index. Let’s say we want to locate the position of « C# » in the pgm_langs list. The assert command may be used to confirm that the element at index 7 is ‘C#’.

print(pgm_langs.index('C#'))
# Output: 7
assert pgm_langs[7] == 'C#'

With pop(), remove an item from an index

Let’s now examine list techniques for Python lists that delete entries. An element at a certain index can be removed and returned using the pop() function. We may infer from the above code sample that language ‘C#’ is located at index 7.

‘C#’ is returned as the element at index 7 when the pop() method is called on the pgm_langs list with 7 as the index, and the element is also removed from the list.

print(pgm_langs.pop(7))
# Output: 'C#'
print(pgm_langs)
# Output: ['Scala', 'Rust', 'Python', 'JavaScript', 'Java', 'Go', 'C++', 'C']

The pop() function removes and then returns one element at the given index. The index specification is optional, though. The pop() function removes the final entry from the Python list and returns it when the index is left blank, as demonstrated:

print(pgm_langs.pop())
# Output: 'C'
print(pgm_langs)
# Output: ['Scala', 'Rust', 'Python', 'JavaScript', 'Java', 'Go', 'C++']

Remove Items Using Remove()

Sometimes you may be aware of the element to delete but not its index. In this situation, you may utilize the remove() function, which accepts an element to remove and removes it. Let’s use the remove() function to eliminate « Java » from the list of pgm_langs.

pgm_langs.remove('Java')
print(pgm_langs)
# Output: ['Scala', 'Rust', 'Python', 'JavaScript', 'Go', 'C++']

With clear(), remove all items

What if you wanted to delete every item from a Python list? Using a loop to go over the list, you can use the remove() function to delete each member as follows:

for lang in pgm_langs:
    pgm_langs.remove(lang)

But is there an alternative? using the clear() function, of course. We can see that when the clear method is used on the pgm_langs list, all of the entries are removed, leaving pgm_langs as an empty list.

pgm_langs.clear()
print(pgm_langs)
# Output: []

Python List Methods in Brief

In a nutshell, this is the syntax for the different list methods:

List MethodSyntaxDescription
1insert()list1.insert(index, elt)Inserts elt at index in list1
2append()list1.append(elt)Adds elt to the end of list1
3extend()list1.extend(list2)Adds elements from list2 to the end of list1
4sort()list1.sort()Sorts the list in place
5reverse()list1.reverse()Reverses list1 in place
6copy()list1.copy()Returns a shallow copy of list1
7count()list1.count(elt)Returns the count of elt in list1
8index()list1.index(elt)Returns index of elt in list1
9pop()list1.pop(index)Removes elt at index and returns it.
10remove()list1.remove(elt)Removes elt from list1
11clear()list1.clear()Removes all elements from list1

Conclusion

I hope you were able to utilize some of the most used list methods in Python after reading this article. Learn more about Python tuples and how they vary from lists in Python as a next step.

Check out this collection of learning materials for beginners if you’re studying Python.

Recommended For You

About the Author: Ismaïl

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *