list() in Python

Video Tutorial
FREE
Lists thumbnail
This video belongs to
Python and SQL for Data Science
8 modules
Certificate
Topics Covered

Overview

In python, we have lots of data structures but sequence is the most basic one among them. The sequence starts from index zero and goes upto (length of sequence - 1).

There are many operations possible in the sequences like adding, multiplying, slicing, membership and comparison etc. Among all the six builtin types of sequences list is most common one about which we are going to study in this article.

In Python, a list is used to store the sequence of different types of data. Python lists are mutable(changeable), which means we can change their elements after they've been formed.

Syntax of list() in Python

The comma (,) separates the elements in the list, which are enclosed in square brackets [].

Example :

If we will print type of list1 and list2, it will give list as a result

Output :

Parameters of list() in Python

In python the list constructor takes a single argument and that is nothing but an object that could be a sequence or collection like tuple, string, set and dictionary.

Example :

Output :

So as we can observe from the above example that list function changes the sequences from string and tuple into list without altering the order of elements in the sequences.

Return Values of list() in Python

Example 1

Output :

So in the above program both the list have same elements but the order of those elements are different in both lists but as we know that the python list is ordered sequence so it will return False when we will compare both of them.

Example 2

Output :

So in the above program both the list have same elements and the order of those elements is also same in both lists and as we know that the python is ordered sequence so it will return True when we will compare both of them.

Example of list() in Python

Example 1

Output :

Example 2

Output :

What is a List in Python?

List in python is used to store the sequence of different types of data. List in python is changeable, which means we can change their elements after they've been formed. However, Python has six data types that can be used to store sequences, with the list being the most common and stable.

List in python can be defined as a collection of distinct types of values or items. The comma (,) separates the elements in the list, which are enclosed in square brackets [].

Python List Methods

Python includes many types of helpful list functions that make working with lists way more simple. Here are a few of the most common list methods.

MethodsDescriptions
1.append()Adds new element to end of the list
2.extend()Extends the list by adding all the specified iterables like list, string, tuples at the end of the list.
3.insert()Inserts an element at the defined index
4.remove()The first occurrence of the specified item is removed from the list. If the provided object is not found, a ValueError is thrown.
5.pop()Returns and removes an item from the list from the specified index position. The list.pop() method removes and returns the final item in the list if no index is given.
6.clear()Removes all elements from the list
7.count()Returns the count of the number of items passed as an argument
8.sort()Sorts elements of the list in ascending order
9.reverse()The index locations of the elements in the list are reversed. The first element will be indexed last, the second element will be indexed second last, and so on. Hence the whole list will be reversed.
10.copy()Returns a copy of the list
11.index()The index location of the first occurence of the specified item is returned. If no item is discovered, a ValueError is thrown.

More Examples

1. Create Python Lists

A list is made in Python by placing items inside square brackets [] and separating them with commas.

Example :

There can be any number of elements in a list, and they can be of different types like integer, string, float etc.

Example :

Another list can also be included as an item in a list. This is referred to as a nested list.

Example :

2. Access List Elements

The elements of a list can be accessed in a number of ways.

Using List Index:

To get to a specific item in a list, we can use the index operator []. In Python, indices begin at 0 and go up from there. As a result, a list with 10 items will have an index ranging from 0 to 9. And if we try to access the index out of this range then an error will be raised that IndexError which means list index out of range. An integer must be used as the index. We can't use floats or other kinds because TypeError will occur.

Click Here,To know more about index() in Python.

Example:

Output :

Nested list elements can also be accessed using nested indexing.

Example :

Output :

Python list support negative indexing. The last index is represented by the index -1, the second last item by the index -2, and so on.

Example :

Output :

3. List Slicing in Python

Using the slicing operator :, we can access a sub list of elements in a list. We can get the sub-list of the list using the following syntax.

Example :

  • start tells about the starting index of the sublist with respect to the original list.
  • stop tells about the stopping index of the sublist with respect to the original list.
  • step is used to skip every nth element in range start.

Output :

As we can see that that in the first print statement we have written the range from 1 to 4 but it is printing the elements till index 3 because whenever we will slice the list then starting index is inclusive but the stopping index is exclusive.

Click here, To know more about List Slicing in Python.

4. Add/Change List Elements

Lists, unlike strings and tuples, are changeable, which means that their elements can be updated. The assignment operator = can be used to update a single item or a group of objects.

Example :

Output :

The append() method can be used to add a single element to the list, whereas the extend() method can be used to add several elements.

Example :

Output :

Two lists can be concatenated or combined using the + operator.

List can be repeated given number of times using the * operator.

Example :

Output :

We may also use the method insert() to insert a single item at a specific index of list. Syntax of the insert() method is given below.

Example :

Output :

5. Delete List Elements

If you know exactly the index of elements which you want to delete, you can use the del method and if you don't, then you can use the remove() method.

Example :

Output :

Now what if we want to delete entire list at one, so for that perform the following operation.

Example :

Output :

Remove() method can be used to get rid of a specific element or pop() to get rid of an item at a specific index.

If the index is not specified, the pop() function removes and returns the last element.

Example :

Output :

6. List Comprehension

In Python, list comprehension is a simple and clever approach to generate new lists from iterables such as tuples, strings, arrays, and lists.

A list comprehension is made up of brackets that hold the expression that is run for each item, as well as a for loop that iterates through each element.

Below is an example which shows that each element is being multiplied by 2 and storing them into a new list that is mul_list.

Example :

Output :

This above code is equivalent to the code given below:

Now, you can see yourself the difference between the length of both codes and can decide which one is more elegant and simple one.

More for or if statements can be included in a list comprehension if desired. Items for the new list can be filtered out using an optional if condition. Here are a few examples.

Suppose we have print the squares of all the even number in the given range. So we will do that using list comprehension as done below.

Example :

Output :

That above code can also be written in a way as given below:

Python List Built-in Functions

The lists can be used with the built-in python functions listed below:

FunctionDescription
1max(list)It returns the list's most large element.
2min(list)It returns the list's most small element.
3len(list)It returns the lenght of the list.
4list(seq)It converts any sequence into list.
5sum()It returns the summation of all the elements in the list.
6reduce()It applies an operation to all of the list elements with the given argument stores the intermediate output and only returns the final summing result.
7any()It returns true if any item of the list is true. if the list is empty, return false
8map()It returns a list of the results after applying the given function to each item of the specified iterable
9all()It returns true if all items is true or if the list is empty
10cmp(list1, list2)It compares the elements of both the lists.

Other List Operations in Python

List Membership Test

Using the keyword in, we can see if an item is present in a list or not. We will get boolean(True/False) value as a result.

Example :

Output :

Iterating Through a List

We can go through each item in a list using a for loop and that going through is nothing but iteration.

Example :

Output :

Conclusion

  • List is mutable and comes with lots of inbuilt functions.
  • List is always preferred among all available sequences.
  • List comprehension is useful in terms of short condition programs.

Read More:

  1. How to Add Elements in List in Python?.
  2. Python list index method.
  3. Comprehensions in Python
  4. Set to List in Python.