Skip to Content

Python Lists: Everything You Need to Know

Python lists are one of the most fundamental data structures in Python. In this blog post, we will discuss everything you need to know about them!

We will cover how to create lists, add and remove items from them, and search through them. We will also discuss some common list operations, such as reversing a list and sorting it. By the end of this post, you should be able to use Python lists with confidence!

  • How to use Python Lists
  • The different ways to create a Python List
  • How to add and remove items from a Python List
  • How to search through a Python List
  • The common operations that can be performed on a Python List

 

Understanding List 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 [ ].

A list can be defined as a collection of values or items of different types. The items in the list are separated with the comma (,) and enclosed with the square brackets [].

For example:
num = [1, 2, 3, 4]
letter = [‘a’, ‘b’, ‘c’, ‘d’]

characteristics of Python List

The list has the following characteristics:

  • The lists are ordered.
  • The element of the list can access by index.
  • The lists are the mutable type.
  • The lists are mutable types.
  • A list can store the number of various elements.

Creating Lists

Lists can be created in a number of ways. The simplest way is to use the list() function:

>>> list(range(0, 101))
[0, 1, … 100]

You can also create a list by specifying the items that make up the list explicitly:
>>> myList = [“apple”, “banana”, “cherry”]

In this example, we create a list of strings called myList. The items in the list are separated by commas, and they appear within square brackets (“[ ]”).

We can also create a list using the range() function:

>>> myList = range(0,101)
[0, … 100]

This will create a list with 101 items, starting from 0 and going up to 100.

We can also create lists using comprehensions or generator expressions:
Comprehensions allow you to create lists by applying a filter or transforming one or more sequences. Here’s an example:
lists = [ i for i in range ( 20 )] # Create a list of the numbers 0-19
print ( lists ) # Output: [0, …,11 , 12 , 13 , 14 , 19 ]

We can also create lists by using concatenation or multiplication operators on sequences:
lists = [ “apple” ] * 50 + [ “orange” ] # Creates a list with 100 items (“apple”, then “orange”)
print ( lists ) # Output: [‘apple’, ‘apple’, …]

4 Ways to Create a List in Python

Access Items in a Python List

We can access individual items in a list by using the index operator []:

lists = [ “apple” , “orange” , “banana” ] # Create a list of strings
print (lists[0]) # Prints first item in list

Lists are zero-indexed, which means that Python stores and retrieves elements starting at position 0 .
We can also use negative indexes to access elements from the end of a list. They start from the end of the sequence instead of the beginning.
Negative indexing is useful for accessing items in large lists where you don’t know how many items are present.

Modify Items in a Python List

We can modify individual items in a list by using the index operator []:
lists = [ “apple” , “orange” ] # Create list of strings
print ( lists [ 0 ]) # Prints first item in list
lists [ 0 ] = “banana” # Changes first item in list to ‘banana’
print ( lists ) # Output: [‘banana’, ‘orange’]

If we try to access an element that doesn’t exist, Python will raise an IndexError exception.

Add Items in List

We can add new items to a list by using the append() function:

>>> myList = [“apple”, “banana”] >>> myList.append(“cherry”)
>>> myList
[“apple”, “banana”, “cherry”]

 

4 Ways to Append List in Python

 

Difference between List Insert append extend methods

  • The insert() method adds a new item at a specific location.
  • The append() method adds a new item at the end of the list.
  • The extend() method adds each of an iterable to the end of the list.

 

4 Ways to Add Items to a List in Python

 

Removing Items in List

We can also remove items from a list by using the del() function:

>>> myList = [“apple”, “banana”, “cherry”]
>>> del myList[0]
>>> myList
[“banana”, “cherry”]

In this example, we delete the first item from the list. The list will now have two items in it.

Difference between List remove pop clear methods

  • The remove() method removes the first matching element and keep the remaining.
  • The pop() method removes the last element by default. You can optionally set a specific index, at which the element will be removed.
  • The pop() method returns the removed item, and thus it’s useful for cases where you need to operate the removed item.
  • The clear() method removes all items.

 

Searching Through Lists

We can search through lists to find a particular item by using the in operator:

>>> fruitList = [“apple”, “banana”, “cherry”]
>>> “pear” in fruitList
False

We can also use the index() function to get an item from a list:

>>> fruitList = [“apple”, “banana”, “cherry”]
>>> fruitList[0]
‘apple’

The index() function takes an item and returns the position of that item within the list. If we try to access a nonexistent item, Python will raise an error.

Sort List Operations

There are many built-in functions in Python for working with lists, including ones that will reverse a list or sort it:

>>> myList = [“apple”, “banana”, “cherry”]
>>> myList.sort()
>>> myList
[“apple”, “banana”, “cherry”]

The sort() function will put the list in alphabetical order by default.

Reverse List Operations

>>> myList.reverse()
>>> myList
[‘cherry’, ‘banana’, ‘apple’]

In this example, we use reverse() function to change the order of our list.

  • The reverse() function will reverse the order of items in a list, so that the last item is now first and vice versa.
  • The reversed() method returns an iterable, not a list, so you have to use list() to generate a list from the iterable.
  • The reverse() method reverses the list in place and thus it returns None.
  • In addition to list objects, the [::-1] method can also be used to reverse other sequences, such as strings and tuples.

Advanced list operations

In this section, we will cover some of the more advanced operations available for lists.

A slice is a subset of list items with a particular sequence. You can create slices by using the [start:stop] syntax:
fruit_list = [ “apple” , “orange” , “banana” ] # Create a new list with three fruits
print (fruit_list) # Output: [‘apple’, ‘orange’, ‘banana’]
print ( fruit_list [ 0 :]) # Prints all elements in list starting from index[0] to end of the list
print ( fruit_list [ – len ( fruit_list ):]) # Prints all elements in list starting from index[-len(fruit_list)] to the end of the list

You can also use negative indices to create slices from the beginning or end of a list.

We can also concatenate two lists together using the + operator, or multiply two lists together using * :

fruit_list = [ “apple” , “orange” ] # Create a new list with two fruits
print ( fruit_list ) # Output: [‘apple’, ‘orange’]
print ( fruit_list + [ “strawberry” ]) # Concatenate a new item to the end of the list ‘apple’, ‘orange’, ‘strawberry’
print ( fruit_list * [ “banana” ]) # Multiply every item in the list by ‘banana’ [‘apple’, ‘orange’, ‘banana’, ‘banana’, ‘stanwaery’]

Understanding Python list comprehension

Python supports a concept called “list comprehensions”. It can be used to construct lists in a very natural, easy way, like a mathematician is used to do.

List comprehensions are also faster than for loops and the built-in map() function because they don’t have the overhead of method calls.

[ i ** i for i in range ( 0 , 11 )] # Output: [0, …, 1024]

Here’s an example that combines two lists if they are not equal:

[( x , y ) for x in [ ‘A’ , ‘B’ , ‘C’ ] for y in [ ‘X’ , ‘Y’ ] if x != y ] # Output: [((‘A’, ‘X’), (‘B’, ‘Y’)), ((‘A’, ‘Y’), (‘B’, ‘X’)), ((‘C’, ‘X’), (‘C’, ‘Y’))]

The list comprehension can be used to do all sorts of things, including filtering and transforming lists. List comprehensions are a very powerful tool that every Python programmer should be familiar with. They provide an easy way to construct lists in a natural way, which can speed up your code significantly. In addition, they are often more readable than for loops or map() functions.

Alternatives to use lists in Python programs

There are several alternatives to using lists in Python programs. Some of the most common are:

  • – Strings: String literals can be used to represent a list of characters.
  • – Tuples: Tuples are similar to lists, but they are immutable.
  • – Sets: Sets are unordered collections of unique items.
  • – Dictionaries: Dictionaries are associative arrays, which means that they map keys to values.

Conclusion

Lists are one of Python’s most versatile data structures. They can contain any type or number of items, which makes them very flexible for use cases like storing user input from an application or even creating your own games! This post should have given you an overview of what lists are and how they work with some examples to help get started using them yourself.