Lists are collection of different elements of different data types although usually they will be of the same data type. It is a container that can hold primitive data types as well as user-created data types. This lessons show how to create and use lists.
- List is a sequence of elements.
- Lists are mutable data structure. We can modify elements of the list using indexing operation.
- Lists are iterable so we can iterate through each item of the list.
Creating Lists in Python
There are couple of ways to create a list.
- Using square brackets
[]. - Using built-in function
list.
Example:
1numbers = [1, 2, 3, 4, 5]
2print(numbers)
In above example, we created a list with elements 1 to 5.
Output:
[1, 2, 3, 4, 5]
We can create empty list using below syntax. Alternatively, we can use list() function as shown below. This function takes in any iterable and returns a list of those elements.
1empty_list = []
2another_empty_list = list()
We can create lists of numbers or string data types or any other data type if we want.
1numbers = [1, 2, 3]
2fruits = ['apple', 'orange', 'banana']
List can also contain multiple data types.
Example:
1mixed_list = [1, 2, True, "banana", False]
We can also create nested lists. These are also called multi-dimensional lists.
1nested_list = [[1, 2], [3, 4]]
We can also pass a range object into list function to create a list.
Example:
1numbers = list(range(5))
2print(numbers)
Output:
[0, 1, 2, 3, 4]
Just like strings, we can use same range function with start, stop and step values to create a list.
1even_numbers = list(range(0, 10, 2)) # [0, 2, 4, 6, 8]
We can create list from any iterable using list() function.
1list("Hello") # ['H', 'e', 'l', 'l', 'o']
List Indexing
Lists are indexed using 0-based indexing. That is the first element of the list is at index position 0 just like strings. We can also use negative indices, i.e. the last element of the list can be accessed easily using -1 index.
Example:
1numbers = [1, 2, 3, 4, 5]
2print(numbers[3]) # 4
3print(numbers[-1]) # 5
Lists are mutable so we can modify each element of the list using their index.
Example:
1numbers = [1, 2, 3, 4, 5]
2print(numbers[3]) # 4
3numbers[3] = 400
4print(numbers[3]) # 400
If we try to access an element at index position, which doesn’t exist in the list, Python interpreter will throw IndexError.
Example:
1print(numbers[5]) # IndexError: list index out of range
To find how many elements are there in a list, we can use built-in len() function. We can also use this function to access the last element and to avoid IndexError for accessing elements.
1print(len(numbers)) # 5
2
3# To access last element of the list, use len() function
4print(numbers[len(numbers) - 1]) # 5
5
6# or even better use negative index
7print(numbers[-1]) # 5
We can also create nested list in which each element itself is one-dimensional list.
1nested_list = [[1, 2], [3, 4]]
2print(nested_list[0]) # [1, 2]
3print(nested_list[0][1]) # 2
List Slicing
We can perform list slicing operations to get a sub-list. This is based on list indices, so again knowledge of indices comes into play. It again works on the same slicing operations like string datatype. We use square brackets to specify the start and end position. The general syntax for slicing operation looks like this.
1lst[start:stop:step]
In slicing operation, the start index element is included and stop index element is excluded in the output list.
Example:
1numbers = list(range(1,11))
2print(numbers[4:6]) # [5, 6]
If we don’t specify start position, it by default starts from the beginning of the list at position 0. If we don’t specify the stop position, it goes upto the end of the list, i.e. len(lst) - 1.
1print(numbers[:3]) # [1, 2, 3]
2print(numbers[5:]) # [6, 7, 8, 9, 10]
By default, the step value is 1, but we can specify different value in the third number in square brackets. We can also omit any of the other values. For example, to get only even numbers from the above numbers list, we can specify step value as 2.
1print(numbers[1::2]) # [2, 4, 6, 8, 10]
Based on List slicing, there is a neat trick to reverse a list.
1print(numbers[::-1]) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
We can combine two lists using + operator.
1list1 = [1, 2, 3]
2list2 = [4, 5, 6]
3print(list1 + list2) # [1, 2, 3, 4, 5, 6]
Unpacking lists
List unpacking is little different from other programming languages. If you’ve background in Javascript then you may find it similar destructing assignment.
In the below code, I have simple list with two values and in the second statement, I’m assigning those values to variables a and b respectively.
1lst = [1,2]
2a, b = lst
3print(a,b) # 1 2
In this, we can assign values from list into multiple variables on the left. We have to make sure to have equal number of variables on the left hand side as the number of elements in the list. If these don’t match, it throws an error.
1a, b, c = lst # ValueError: not enough values to unpack (expected 3, got 2)
Iterating through List
Lists are iterable and we can iterate through each element of the list using for loop.
Example:
1fruits = ["apple", "orange", "banana"]
2
3for fruit in fruits:
4 print(fruit)
Output:
apple
orange
banana
If we also need the index of each element, we can use the built-in enumerate function. This function returns a tuple containing index and the actual value obtained by iterating through the list.
Example:
1cities = ["New York", "London", "New Delhi", "Sydney"]
2
3for index, city in enumerate(cities):
4 print(f"City {index}: {city}")
Output:
City 0: New York
City 1: London
City 2: New Delhi
City 3: Sydney
List Methods
There are lots of built-in methods that we can use to manipulate lists. Methods are similar to function but they work on specific data types. In this case, they work on lists. Methods are usually invoked using dot (.) notation. We specify list followed by dot and then the method name.
Inserting elements
We can insert elements into a list using insert method which takes the position where we want to insert new element and the element we want to insert.
1numbers = [0, 1, 2, 3]
2numbers.insert(4, 400)
3print(numbers) # [0, 1, 2, 3, 400]
We can append an element at the end using append
1numbers.append(400) # [0, 1, 2, 3, 400]
Removing Elements
We can use pop to pop out an element from the list and return it. The pop function can also take an index to remove the element from a specific index position.
1last = numbers.pop()
2print(last) # 400
3print(numbers) # [0, 1, 2, 3]
4numbers.pop(2)
5print(numbers) # [0, 1, 3]
We can also use del operator to remove an element from the list. This does not return that element, it only removes it from the list.
1del numbers[-1]
2print(numbers) # [0, 1]
If we want to remove specific element by value, we can use remove method. This takes the element to remove and not the index position unlike pop method. Also, if there are multiple occurrences of the same element, it will remove only the first instance of that element.
1numbers = [1, 2, 3, 400, 5, 400]
2numbers.remove(400)
3print(numbers) # [1, 2, 3, 5, 400]
How to Join Python lists
As we saw previously, we can append two lists using + operator. This returns new list and does not modify existing one.
1numbers = [1, 2, 3]
2others = [4, 5, 6]
3print(numbers + others) # [1, 2, 3, 4, 5, 6]
4print(numbers) # [1, 2, 3]
5print(others) # [4, 5, 6]
If we want to modify existing list, we can use extend method which takes another list as argument.
1numbers = [1, 2, 3]
2others = [4, 5, 6]
3numbers.extend(others)
4print(numbers) # [1, 2, 3, 4, 5, 6]
How to compare Python Lists
We can compare two lists using ==. This checks each list elements and if they are all equal, then only this returns True.
1numbers = [1, 2, 3]
2others = list(range(1, 4))
3another = list(range(3))
4print(numbers) # [1, 2, 3]
5print(others) # [1, 2, 3]
6print(another) # [0, 1, 2]
7print(numbers == others) # True
8print(numbers == another) # False
These are two separate instances of lists. We can verify this by checking their object id using id() function. This will give different result every time we execute it.
1print(id(numbers)) # 2074723580608
2print(id(others)) # 2074720324800
How to find elements in a List
To find specific element from a list, there are multiple options.
- Iterate through the list and search for that specific item. This is not so useful as there are better methods mentioned below.
- Use the
index()method to find given element. - Use
inoperator.
1fruits = ["apple", "orange", "banana"]
2banana_index = fruits.index("banana")
3print(banana_index) # 2
If the list does not contain an element we are trying to index, then index method throws ValueError.
1fruits.index("pineapple") # ValueError: 'pineapple' is not in list
There is much better option to find elements in a list using in operator. This does not throw error when element is not found in the list and is the most preferred method for searching a list. This returns boolean result whether the item exists or not.
1fruits = ["apple", "orange", "banana"]
2"apple" in fruits # True
3"pineapple" in fruits # False
To avoid this error with index() method, we have to check whether an item exists before getting the index position of the element.
1pineapple_position = fruits.index("pineapple") if "pineapple" in fruits else -1
2print(pineapple_position) # -1
How to sort List elements
Lists can be sorted using built-in function sorted(). This returns a brand new list with elements sorted in ascending order by default.
1fruits = ["apple", "orange", "banana"]
2print(sorted(fruits)) # ['apple', 'banana', 'orange']
3print(fruits) # ['apple', 'orange', 'banana']
If we want to sort the existing list in-place, we can invoke a method sort() on that list. This function returns None.
1fruits = ["apple", "orange", "banana"]
2fruits.sort()
3print(fruits) # ['apple', 'banana', 'orange']
If we want to create a reverse list, we could pass keyword argument reverse=True to this sort() method. If we don’t want to modify existing list, we can call sorted() function with reverse=True.
1fruits = ["apple", "orange", "banana"]
2sorted_fruits = sorted(fruits, reverse=True)
3print(sorted_fruits) # ['orange', 'banana', 'apple']
4print(fruits) # ['apple', 'orange', 'banana']
5fruits.sort(reverse=True)
6print(fruits) # ['orange', 'banana', 'apple']
Other Functions
We can repeat elements of a list type by * operator.
1numbers = [1, 2, 3]
2print(numbers * 2) # [1, 2, 3, 1, 2, 3]
There are built-in functions to find sum, max and min from a list.
1numbers = [1, 2, 3]
2print(sum(numbers)) # 6
3print(min(numbers)) # 1
4print(max(numbers)) # 3
We can create a string from a list of string by joining all elements with a separator using join() function from string.
1fruits = ["apple", "orange", "banana"]
2all_fruits = ", ".join(fruits)
3print(all_fruits) # apple, orange, banana
Similarly, we can split a string and create a list of string by splitting a list with specific delimiter using split() method on string.
1colors = "red, black, white".split(", ")
2print(colors) # ['red', 'black', 'white']
3print("one-two-three".split("-")) # ['one', 'two', 'three']
We can clear all elements of a list using clear() method.
1numbers = [1, 2, 3]
2print(numbers) # [1, 2, 3]
3numbers.clear()
4print(numbers) # []
List Comprehension
List comprehensions provide succinct way to write loops and other list manipulations. This looks like below.
1[expression for elem in list]
Let’s see how we write loops and then we will try to convert that to list comprehension.
1fruits = ["apple", "orange", "banana"]
2# Create list with only first character from above fruits list.
3lst = []
4for fruit in fruits:
5 lst.append(fruit[0])
6print(lst) # ['a', 'o', 'b']
This could be converted into list comprehension like this.
Example:
1fruits = ["apple", "orange", "banana"]
2lst = [fruit[0] for fruit in fruits]
3print(lst) # ['a', 'o', 'b']
Similarly, let’s say we have numbers list and we want to create another list whose elements are going to be the square of the original list. We could do that using loop or list comprehension.
Below is normal way to do it using loop.
1numbers = [1, 2, 3, 4, 5]
2squares = []
3for number in numbers:
4 squares.append(number * number)
5print(squares) # [1, 4, 9, 16, 25]
Using List comprehension it looks like this.
Example:
1numbers = [1, 2, 3, 4, 5]
2squares = [number * number for number in numbers]
3print(squares) # [1, 4, 9, 16, 25]
We can also include simple conditionals in list comprehension to filter out certain elements of the source list. Below is an example of creating new list with only squares of even numbers from another list containing even and odd numbers.
1numbers = [1, 2, 3, 4, 5]
2even_squares = [number * number for number in numbers if number % 2 == 0]
3print(even_squares) # [4, 16]


Comments