List and Methods in a List
Lists in Python
The first data structure that is often encountered in Python is that of a list. They can be used to store multiple items in a single variable and effectively act as you would expect a normal list would behave such as your shopping lists. they are one of the four in-built data types in Python that can be used to store collections of data alongside tuples, sets, and dictionaries.
Their key characteristics are that they are:
- Mutable: They can be changed once they have been defined
- Ordered: They maintain their order unless explicitly changed
- Indexable: The fact that they maintain their order allows us to access specific items if we know their place on the list
They can also contain duplicate records. This is important as they influence how lists can be used in programs, as the fact that they can be changed may mean you may not want to use them if you want your data to be fixed, or the fact that you can access information by their index may be useful in information retrieval later on.
Creating a list
To create a list we can use two main methods:
- Using
[]
to enclose what we want to contain in the list with items separated by commas - Using the
list()
function which can be used to convert other data structures to lists or take a list as an argument
In this article, we will discuss the following Python List Methods.
1.append()
The append() method adds an item to the end of the list.
2.clear()
The clear() method removes all items from the list.
3.copy()
The method returns a new list. It doesn’t modify the original list.
4.count()
The method returns the number of times the specified element appears in the list.
5.extend()
The method adds all the elements of an iterable (list, tuple, string, etc.) to the end of the list.
6.index()
The method returns the index of the given element in the list.
7.insert()
The insert() method inserts an element to the list at the specified index.
8.pop()
The method removes the item at the specified index.
9.remove()
The method removes the first matching element (which is passed as an argument) from the list.
10.reverse()
The method reverses the elements of the list.
11.sort()
The method sorts the list ascending by default.
#vevcodelab