What is list () in python do?

Guidelines to use lists in Python

1. What is a Python list?

A list is an ordered and mutable Python container, being one of the most common data structures in Python. To create a list, the elements are placed inside square brackets ([]), separated by commas.

As shown above, lists can contain elements of different types as well as duplicated elements.

2. Create a list with list() constructor

Lists can also be created with the built-in function list([iterable]). This function takes as argument an iterable (i.e. any type of sequence, collection, or iterator), returning a list with the items of the input object.

As shown above, we can easily create lists not only from Python built-in containers but also from Numpy arrays and Pandas series, among others iterables.

We can also use the list() constructor without any input parameter. In this case, the constructor returns an empty list.

3. Access elements in a list

Lists are ordered sequences of elements and like other ordered containers in Python, they are indexed using a starting index of 0. To access an element in a list, we provide the index (an integer) inside square brackets ([]) as follows.

As shown above, an IndexError is raised when trying to access an index that is outside the range of the list.

We can also use a negative value to access an item from the end of the list, where -1 refers to the last element, -2 to the second last element and so on.

To access multiple elements, we employ python’s slicing operator:

[start: stop: step]

When slicing, it is important to recall that the start index is inclusive and the end index is exclusive.

Remember that we can access and slice elements of a list because they are ordered containers. In Python, containers can be ordered (order defined), or unordered sequence of elements (order undefined) where we only care if the object contains the element, but not its position. For instance, we can easily access a value in a list as we explained before; however, if we try to access an element of a set we get a TypeError, since elements have not a particular position inside a set.

4. Modify items in a list

We can modify an item of a list by giving the index or indexes in square brackets on the left-hand side of the assignment operator (as we access or slice a list), and the new values on the right-hand side.

The code below shows how we can update a single or multiple elements in a list as explained before.

It is possible to modify lists in-place because lists are mutable objects. Mutability refers to the possibility of changing the values of an object. Mutable objects can change their values, while immutable objects can not be altered. For instance, we can modify an item of a list; however, it is not possible to change a tuple in-place, since tuples are immutable objects; their values cannot be modified.

5. Remove elements from a list

There are three ways of removing elements from a list:

  • Using the del keyword
  • Using the list.remove(x) method
  • Using the list.pop([x]) method

The del keyword

We can delete one or multiple items of a list using the del keyword, providing the indexes we want to remove inside square brackets([]) in the following fashion:

As shown above, we can use the del keyword not only to remove items from a list, but also to delete a reference to an object.

The pop method

The list.pop([x]) method removes the item at the given index, and returns it. If the index is not provided, the list.pop() method removes and returns the last item of the list. An IndexError is raised when trying to remove an index that is outside the range of the list.

The remove method

The list.remove(x) method deletes the first matching element from the list, and returns None. If the element is not present in the list, a ValueError exception is raised.

6. Insert an element in a list

To insert an element in a list, we can employ:

  • The list.insert(i,x) method
  • The list.append(x) method

The insert method

The list.insert(i,x) method inserts an element x at a given index i, and returns None.

As shown above, the first argument i is the index of the element before which we insert an item. That is why, if we provide an index of -1 as input, the element is inserted in the second-to-last position rather that at the end of the list. To insert an item at the end of the list, we have to provide the length of the list as input.

We can add with the insert method not only a primitive data type (integer, float, string, or boolean) but also a Python container (e.g. a list) as shown below.

The append method

The list.append(x) method adds an item to the end of the list, being equivalent to list.insert(len(list), x).

As shown above, the .append() method modifies the list in-place, returning None.

7. Sort a list

The sorted function

To sort elements of a list, we can use both the sorted function and the sort method. The sorted function returns a sorted list, but the list provided as input remains unchanged.

This function has the following syntax:

sorted(iterable[, key][, reverse])

The first parameter is the iterable that we want to sort (in this case a list). The two following parameters, key and reverse, are optional, allowing us more complex sorting. We will see that later on!

The sort method

Unlike the sorted function, the sort method sorts the list in-place, returning None.

The sort method has the following syntax with two optional parameters as well: key and reverse.

list.sort(key=…, reverse=…)

The code below shows how we can use both the sorted function and the sort method to sort the elements of a list.

Additional parameters: reverse and key

The sorted function and the sort method sort the elements in ascending order, unless we indicate otherwise, providing the parameter reverse=True.

Another important parameter is key. We can sort a list based on the value returned by the function provided in the key parameter. We apply the function to each element of the list, and then we sort the elements based on the value returned by this function. The key parameter can contain built-in, anonymous, or normal functions as well as methods.

In the following examples, we use the key parameter to:

  1. Sort a list of strings by its length.

2. Sort a list of strings by the number of vowels.

3. Sort a nested list by the third value.

8. Reverse a list

The reversed function

To reverse the elements of a list, we can use both the reversed(seq) function and the list.reverse() method. The reversed function returns the reversed iterator of the given sequence, remaining the sequence provided as input unchanged. In comparison with the sorted function, the reversed function does not return a list so if we want to obtain a list, we have to use the list() constructor.

The reverse method

Unlike the reversed function, the reverse method reverses the list in-place, returning None.

9. Concatenate two list

There are multiple ways to join two lists in Python. The + operator is one of the simplest ways; in fact, we can also use this operator to concatenate another type of containers such as strings or tuples.

The + operator allows you to concatenate more than two lists as well.

Another way to concatenate two list is using the list.extend(iterable) method. This method extends the list by appending all the items from the iterable.

As shown above, the list.extend(iterable) method modifies the list in-place, adding the elements from the iterable at the end of the list. The iterable provided as input remains unchanged, and the method returns None.

As I mentioned before, there are multiple ways to concatenate lists. The following article explains alternative modes to join two list in Python.

10. Check if an element exists in a list

To check whether an element exists in a list, we have to use a membership operator. Membership operators are used to test whether a value is found in a sequence (e.g. strings, lists, tuples, sets, or dictionaries). There are two membership operators, as explained below.

  • in → Evaluates to True if the object on the left side is included in the object on the right side.
  • not in → Evaluates to True if the object on the left side is not included in the object on the right side.

As shown above, membership operators (in and not in) can be used to check whether an element exists in a list, but they can also be used with other sequences in the following manner.

11. Copy a list

To copy a list, we can simply use the list.copy() method. This method returns a shallow copy of the list. We have to be careful with shallow copies, since if your list contains another container-objects like other lists, tuples, or sets, they will be referenced again and not duplicated.

To avoid this problem, we can create a deep copy using the copy.deepcopy(x) function (defined in the copy module) as follows:

The difference between shallow copies and deep copies is only relevant when the list contains other objects like lists (nested lists), since those objects will be referenced instead of duplicated (shallow copy). To create a fully independent clone of the original list, we have to make a deep copy.

It is important to bear in mind that the = operator does not make a copy of the list. It is just another name to refer to the same list, meaning any modification to the new list is reflected in the original one.

12. Determine the length of the list

To determine how many elements the list contains, we can use the len() function. This function returns the number of items of an object. The input of the function can be a list, but also another type of sequence such as a string, dictionary, tuple, or set.

13. List comprehensions

For loops can be used to create lists in Python; however, list comprehensions provide a more elegant and simple syntax to rewrite loops. In addition, they are faster than traditional for loops.

Syntax : [Expression for vars in iterable]

In the following code block, we create a new list of cities, containing capitalized names.

As shown above, we create a new list in three steps.

  1. Create an empty list (cities_capitalized)
  2. Loop through the list (cities)
  3. Append the capitalized names to the new list (cities_capitalized)

However, we can get the same result with only a line of code by using list comprehensions.

We can also use conditional statements with list comprehensions to filter out unwanted data. In the following code block, the conditional statement filters out odd numbers from a list.

As you can see, list comprehensions are an elegant and compact way to create lists. However, very long list comprehensions can result confusing for the reader. For this reason, its use should be limited to simple statements.

14. Alternative container: deque

The deque object (defined in the collections module) is a like-list container optimized for adding and removing items from either sides (right and left).

We can use the methods .append(x) and .extend(iterable) to add elements to the right side of the deque object, as we did previously with lists. However, unlike lists, the deque object supports the methods .appendleft(x) and .extendleft(iterable) to add elements to the left side.

In addition to adding items, the deque object also supports the .pop() and .popleft() methods to remove elements from either sides.

If you want to know more about the deque container, take a glimpse at the documentation.

15. Create a Pandas DataFrame from a list.

A Pandas DataFrame is a two-dimensional tabular data where each row represents an observation and each column a variable. A Pandas DataFrame can be created using the pandas.DataFrame constructor. Although this function accepts as input multiple Python containers, one of the most common ways to create a data frame is using a nested list as input.

As we can observe, the default indexes are integers (beginning at 0). We can modify these indexes by passing a list to the parameters index and columns in the following manner.

As I previously said, there are multiple ways to create pandas data frames. To know more ways, you can visit the following link. :)

List are the most important Python built-in container, being a key aspect when programming in Python to understand them properly. Besides the official Python documentation, there are multiple web pages where you can find detailed explanations of how to use lists, along with examples.

I am planing to do a set of articles about Python containers. So far, guidelines to use dictionaries and lists are finished!

Sets, strings and tuples will be covered in the future 💪

Thanks for reading 👧

Amanda

What is the use of list () Explain with example?

A list is an ordered data structure with elements separated by a comma and enclosed within square brackets. For example, list1 and list2 shown below contains a single type of data. Here, list1 has integers while list2 has strings. Lists can also store mixed data types as shown in the list3 here.

What is list function in Python with example?

Python list() function takes any iterable as a parameter and returns a list. In Python iterable is the object you can iterate over. Some examples of iterables are tuples, strings, and lists. Syntax: list(iterable)

What does list mean in Python?

A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements. Each element or value that is inside of a list is called an item. Just as strings are defined as characters between quotes, lists are defined by having values between square brackets [ ] .

What is the purpose of using list?

Lists can also be used to keep track of all the useful weblinks and articles that you want to read, organized into different categories that can range from news stories, recipes, designs any topic that you can possibly be interested in.