Python Lists: Everything You Need To Know

Python Lists

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.

Lists

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

Literal Syntax

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]

list()

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.

Example:

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 Comprehension

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.

Example:

a = ["red", "blue", "black"]
print(a[1]) # 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[1] = "green"
print(a) # ['red', 'green', 'black']

Add/Delete List Elements

There are plenty of methods for adding and removing items from Python lists:

  • append()
  • insert()
  • extend()
  • pop()
  • remove()
  • clear()

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 = [1]
a.extend([2, 3])
print(a) # [1, 2, 3]

It works in a similar manner to the plus operator:

a = [1]
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:

Summary

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.

Leave a Reply

Your email address will not be published. Required fields are marked *