A Beginner’s Guide to Python Lists

Python lists often perform the function of arrays in other languages.

What is a Python List?

Lists are one of the most important data structures in Python programming. A list is a collection of items, not necessarily of the same type, that are ordered and changeable. Lists are written with square brackets and the items are separated by commas.

Here is an example of a list in Python:

['apple', 'banana', 'orange', 'mango']

Creating Lists in Python

There are several ways to create a list in Python

Using Square Brackets and Commas

To create a list in Python, you can use the square brackets and separate the items with commas.

fruits = ['apple', 'banana', 'orange', 'mango']

Using the list() Function

You can also use the list() function to create a list.

fruits = list(('apple', 'banana', 'orange', 'mango'))

Using the range() Function

You can also create a list with the range() function. The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (also by default), and ends 1 step short of a specified number (this can take a little practice to get used to).

numbers = list(range(10))
print(numbers)  # Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

You can also specify the start and step values in the range() function.

even_numbers = list(range(2, 11, 2))
print(even_numbers)  # Output: [2, 4, 6, 8, 10]

Accessing and Modifying Python List Items

You can access the items of a list by referring to the index number. The index numbers start at 0 for the first item, 1 for the second item, and so on.

fruits = ['apple', 'banana', 'orange', 'mango']
print(fruits[0])  # Output: 'apple'
print(fruits[1])  # Output: 'banana'

You can also use negative indexing to access the items of a list. The index -1 refers to the last item, -2 refers to the second last item, and so on.

fruits = ['apple', 'banana', 'orange', 'mango']
print(fruits[-1])  # Output: 'mango'
print(fruits[-2])  # Output: 'orange'

You can change the value of an item in a list by referring to its index number.

fruits = ['apple', 'banana', 'orange', 'mango']
fruits[1] = 'grapes'
print(fruits)  # Output: ['apple', 'grapes', 'orange', 'mango']

Using the append() Method with Python Lists

Appending items to a list is a very common and important operation. You can use the append() method to add an item to the end of a list.

fruits = ['apple', 'banana', 'orange', 'mango']
fruits.append('pineapple')
print(fruits)  # Output: ['apple', 'banana', 'orange', 'mango', 'pineapple']

Using the insert() Method with Python Lists

You can use the insert() method to add an item at a specific position in a list.

fruits = ['apple', 'banana', 'orange', 'mango']
fruits.insert(1, 'grapes')
print(fruits)  # Output: ['apple', 'grapes', 'banana', 'orange', 'mango']

Removing Python List Items

There are many situations where you might want to remove an item from a list, and there are several different ways to achieve this. For example, you can remove an item from a list using the remove() method.

fruits = ['apple', 'banana', 'orange', 'mango']
fruits.remove('banana')
print(fruits)  # Output: ['apple', 'orange', 'mango']

You can also use the pop() method to remove an item from a list. The pop() method removes the item at the specified index, or the last item if no index is specified, as well as returning it.

fruits = ['apple', 'banana', 'orange', 'mango']
fruits.pop()
print(fruits)  # Output: ['apple', 'banana', 'orange']

fruits.pop(0)
print(fruits)  # Output: ['banana', 'orange']

You can use the del statement to remove an item at a specific index or a range of items.

fruits = ['apple', 'banana', 'orange', 'mango']
del fruits[1]
print(fruits)  # Output: ['apple', 'orange', 'mango']

del fruits[0:2]
print(fruits)  # Output: ['mango']

Python List Slicing

Python lists are very versatile. One of the many useful things you can do with them is “slicing.”

Suppose we have a list of numbers:

my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

We can slice this list using the colon (:) operator. Here are a few examples:

Get a sublist from index 2 to index 5 (exclusive):

sub_list = my_list[2:5]
print(sub_list)
# Output: [30, 40, 50]

Get a sublist from the beginning of the list to index 4 (exclusive):

sub_list = my_list[:4]
print(sub_list)
# Output: [10, 20, 30, 40]

Get a sublist from index 6 to the end of the list:

sub_list = my_list[6:]
print(sub_list)
# Output: [70, 80, 90, 100]

Get a sublist with every other element:

sub_list = my_list[::2]
print(sub_list)
# Output: [10, 30, 50, 70, 90]

Other Python List Operations

The len() is function to find the length of a list. E.g:

fruits = ['apple', 'banana', 'orange', 'mango']
print(len(fruits))  # Output: 4

This is often used in conjunction with range(), as in for i in range(len(xs)). xs is a common name for a list, meaning, “my values,” as in plural of “x.”

You may also wish to sort a Python list. You can use the sorted() function to sort a list in ascending order.

fruits = ['apple', 'banana', 'orange', 'mango']
sorted_fruits = sorted(fruits)
print(sorted_fruits)  # Output: ['apple', 'banana', 'mango', 'orange']

You can also use the sort() method to sort a list in ascending order.

fruits = ['apple', 'banana', 'orange', 'mango']
fruits.sort()
print(fruits)  # Output: ['apple', 'banana', 'mango', 'orange']

You can also add the argument reverse=True to either of these. Notice that the sorted() method doesn’t actually modify the list, whereas sort() does – make sure to choose the one that best suits your purpose.

You can use the reverse() method to reverse the order of a list.

A great and fun way to reverse a list is to use the “alien smiley” operator, like so:

my_list = ["one", "two", "three"]
print(my_list[::-1])  # Output: ['three', 'two', 'one']

This works by using the start, end and step parameters of the Python list-slicing syntax is such as way as to say – “go from the end the the beginning in steps of -1.”

fruits = ['apple', 'banana', 'orange', 'mango']
fruits.reverse()
print(fruits)  # Output: ['mango', 'orange', 'banana', 'apple']

There are an enormous number of algorithms which depend upon lists in Python. Python lists often perform the function of arrays in other languages. Arrays do not allow mixed data types and are of fixed size, but you will often see “list” used synonymously with “array” in informal settings. Becoming familiar with array algorithms is very important as a developer. Here are some of the most common ones:

  • Linear Search
  • Binary Search
  • Bubble Sort
  • Selection Sort
  • Insertion Sort
  • Quick Sort
  • Merge Sort
  • Counting Sort
  • Radix Sort
  • Heap Sort
  • Shell Sort
  • Bucket Sort
  • Topological Sort
  • Minimum Spanning Tree
  • Depth First Search
  • Breadth First Search
  • Dijkstra’s Algorithm
  • Bellman Ford Algorithm

It is well worth spending time studying some of these to develop you ability as a developer. If you want to get into the wonderful world of algorithmic thinking with Python, I recommend my course:

Algorithmic Thinking with Python: Foundations Video Course

Algorithmic Thinking with Python - Foundations Video Course

An introduction to algorithmic thinking with Python. Only basic knowledge of Python needed. Develop you algorithmic thinking through puzzles and programming activities.

  • Brute force algorithms
  • Tracing and debugging algorithms
  • Time complexity of algorithms
  • Decrease and conquer strategy
  • Greedy algorithms

I hope this article was helpful in understanding lists and how to create and manipulate them in Python.

Sharing is caring!

Leave a Reply

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