With lists, Python developers can work with multiple values at the same time by putting them in a single place. They are a basic data structure of which you need to have a good understanding to write your programs better.
In this article, we will learn what Python lists are and how to work with their items.
A Python list is an ordered collection of items (also known as elements) of any data type. Lists are one of the three basic sequence types besides range objects and tuples. They are mutable, meaning you can modify lists, such as adding or removing their elements.
Lists are one of the most popular data structures in Python. They accept any mixture of objects and are a good choice for storing dynamic data for your applications.
In many ways, lists resemble the structure of Python strings. Each item has a unique index to determine its position in the list. Python lists use zero-based indexing. The first item of a list has the index 0, while the index of the last one equals the list’s length minus one.
On top of that, lists also share many operators and methods with strings. In fact, you can apply all of Python’s common and mutable sequence operations to lists.
Create A List
The simplest way to create a list is to assign a variable to a list literal. In Python, list literals are sequences of expressions that are separated by commas and enclosed in square brackets.
Here are some examples of list literals:
[1, 2, 3, 4] ["learnshareit", "quora", "reddit"] 
As you have seen, you can put integer and string values into a list. The final list literal has no element and represents an empty list. You can assign any of them to a variable. When you request it to print a list with the print() function, Python returns the literal that represents that list, including the square brackets and the commas separating its items.
a = [1, 2, 3, 4] print(a) # [1, 2, 3, 4] print(type(a)) # <class 'list'>
Remember that you are free to make a mixed sequence of values of different data types. This is also a valid list in Python:
[1, "learnshareit", 3, "python"]
You can even use other lists as items in a parent list. For example, this is a list of lists:
[[1, 2], ["learnshareit", "quora"]]
Python evaluates the value of every item in the list literal, including variables and other expressions:
x = 5 y = 2 a = [x, x - y] print(a) # [5, 3]
The type constructor list() can also be used to create a list from the items of an iterable. The items in the returned list will have the same value and order as the items in the provided iterable.
list() supports creating lists from iterator objects, iteration-capable containers, and sequences.
list("python") # ['p', 'y', 't', 'h', 'o', 'n']
And, of course, you can use list() on a list literal:
list([1, 2, 3, 4]) # [1, 2, 3, 4]
Note: check out this guide to learn how to convert a map object to a list.
List comprehensions are an advanced technique, but they provide an elegant way to create lists from existing iterables.
a = [ b for b in "python"] print(a) # ['p', 'y', 't', 'h', 'o', 'n']
In this example, a is assigned to a new list that contains every item of the iterable “python”. You can change the expression before the keyword “for” to modify the values of the items:
a = [ x*x for x in (1, 2, 3, 4)] print(a) # [1, 4, 9, 16]
This list comprehension takes all the elements in the list (1, 2, 3, 4) and squares them. The results are the elements of the list “a”.
Access List Elements
You can access any item in a list by providing its index – the position of that item in the list – in square brackets.
a = ["red", "blue", "black"] print(a) # blue
As Python indexes a list from 0, not 1, the index 1 is actually the second item in the list. Negative indexes are also valid. The final item in a list will have the index -1, and the direction of indexing starts from it towards the first item.
print(a[-2]) # blue
You can slice a list and access a portion created by that slice by providing a start and stop position:
a = list("abcdef") a[1:4] # ['b', 'c', 'd']
In this example, Python starts the slicing operation at the second item and stops right before the fifth item.
Change List Elements
Unlike data types like strings and tuples, lists are mutable. Their contents and structures can be changed.
You can use the subscript operator above to access and replace items in lists:
a = ["red", "blue", "black"] print(a) # ['red', 'blue', 'black'] a = "green" print(a) # ['red', 'green', 'black']
Add/Delete List Elements
There are plenty of methods for adding and removing items from Python lists:
You can use the append() method to add ad items to the end of a list:
a = ["a", "b", "c", "d"] a.append("e") print(a) # ['a', 'b', 'c', 'd', 'e']
Meanwhile, insert() gives you the ability to choose the position where you want to add a new item. This method needs another argument: the index of an existing item in the list (the new item will be inserted right before it).
This means if you provide insert() with the index 0, it will add the new item at the beginning of the list:
a = ['a', 'b', 'c', 'd', 'e'] a.insert(0, "z") print(a) # ['z', 'a', 'b', 'c', 'd', 'e']
Use the method extend() when you want to add all the elements of another iterable (such as a second list) to the end of an existing list.
a =  a.extend([2, 3]) print(a) # [1, 2, 3]
It works in a similar manner to the plus operator:
a =  a = a + [2, 3] print(a) # [1, 2, 3]
To remove an item at a given position, use the method pop(). If you don’t provide it with an index, it will remove the last item in the list. It is important to note that this method has a returned value (which is the item that it has removed).
a = ['a', 'b', 'c', 'd', 'e'] a.pop(2) # 'c' print(a) # ['a', 'b', 'd', 'e'] a.pop() # 'e' print(a) # ['a', 'b', 'd']
The remove() doesn’t use indexes for the deletion operation. Instead, it removes the first item that matches the value you provide.
a = ['a', 'b', 'a', 'd', 'e'] a.remove('a') print(a) # ['b', 'a', 'd', 'e']
Notice how the first item ‘a’ is removed, but the second remains in the list.
Tutorials about Python Lists
Some articles related to Python Lists that you may be interested in:
- Remove an element from a list by index in python
- Convert a list of characters into a string in Python
- Split the elements of a list in Python
- Convert a Map object to a List in Python
- Create a list with same value repeated N times in Python
- Join a list of lists in Python
- Multiply each element in a list by a number in Python
- split a string into a list of characters in python
- Add two lists element-wise in Python
- Convert a list of integers to a list of floats in Python
- Multiply all elements in a List in Python
- Split a word into a list of letters in Python
- Multiply two lists element-wise in Python
- Get the first element of each tuple in a list in Python
- Sort a list of tuples by the second element in Python
- Get A List Of All Enum Values In Python
- Get the length of a List in Python
- Add user input to a list in Python
- Join a list with a newline character in Python
- Check if any item in a list is None using Python
- Remove \r\n from a string or list of strings in Python
- Python lists of dictionaries
- Python sort list of dictionaries
- Differences between lists and dictionaries in python
- Remove duplicates from a list of lists in Python
- Join a list of strings wrapping each string in quotes in Python
- Python filter list of dictionaries
- Python list of dictionaries to dataframe
- Sum the values in a list of dictionaries in Python
- Replace None values in a List in Python
- Sum a list of float numbers in Python
- Calculate sum using a list comprehension in Python
- Check if all items in a list are None in Python
- Get the length of a ‘filter’ object in Python
- Use map() to convert strings to integers in a Python list
- Append a range to a list in Python
- Delete a JSON object from a list in Python
- Convert a list of tuples to a list of lists in Python
- How to join specific list elements in Python
- Zip with list output instead of tuple in Python
- Join a list of integers into a string in Python
Python lists allow you to manipulate a sequence of objects of any data type. From a few items to millions of them, you can always rely on this flexible and readily accessible data structure.
My name is Robert. I have a degree in information technology and two years of expertise in software development. I’ve come to offer my understanding on programming languages. I hope you find my articles interesting.
Name of the university: HUST