Python Lists – Learn to store multiple values in Python
In this article, let’s learn about Python Lists.
List is one of the most powerful data structures in Python. The List data type is made with so much of efforts and every programmer from beginner, intermediate to an expert should understand how it works.
So let’s go ahead and dive into the lists.
What are Python Lists?
Python does not have arrays like Java or C++. Arrays are data structures which hold multiple values.
Python does not have arrays but it has lists. Lists are mutable collections of objects.
This is an example:
values=['milk','cheese',12, False]
- Lists are ordered. We can index them and access values. We will see how to do this in the next heading.
- Lists are heterogeneous. A list can contain different types of elements.
- Lists are mutable. You can change values in them.
Creating Lists in Python
You can create lists in many ways:
>>> items=[1,2,3] >>> items
Output:
>>> items=list('123') >>> items
Output:
>>> items=['123'] >>> items
Output:
>>> items=[] >>> items.append(7) >>> items
Output:
>>> items=[1, 2, False, [4, 5]] >>> items
Output:
You can use the in-built list() function to convert another data type into a list. It can also create an empty list without parameters.
Indexing Lists in Python
Like strings, we can index lists to access their values. Indexing starts at 0.
Let’s take an example.
>>> values
Output:
>>> values[2]
Output:
12 is the value at index 2.
1. Positive Indexing
Indexing left to right, starts at 0.
>>> values[1]
Output:
2. Negative Indexing
Indexing right to left, starts at -1.
>>> values[-1]
Output:
Slicing Lists in Python
We can slice lists as well. This gives us only a part of the list. Slicing can take one, two or three values – start, stop and step.
Let’s take examples here as well.
>>> values #list
Output:
>>> values[:] #complete list
Output:
>>> values[:2] #upto index 1
Output:
>>> values[2:] #from index 2 to end
Output:
>>> values[-3:] #from index -3 to end
Output:
>>> values[1::2] #from index 1 to end with a step of 2
Output:
Modifying Lists in Python
Unlike strings, lists are mutable. You can change its values.
Let us take a few examples.
>>> values
Output:
>>> values[1]='bread' >>> values
Output:
values[1] is now ‘bread’ and not ‘cheese’.
>>> values[1:1]=['cheese','eggs'] >>> values
Output:
If we assign this list to the slice values[1:1], it adds the values ‘cheese’ and ‘eggs’ between indices 0 and 1.
Adding Elements in Python Lists
Lists are mutable, so we can also add elements later. We can do this in many ways.
1. append()
We can append values to the end of the list. We use the append() method for this. You can use this to append single values to the list – value, list, tuple.
>>> nums=[1,2,3] >>> nums.append(4) >>> nums.append([5,6]) >>> nums.append((7,8)) >>> nums
Output:
2. insert()
You can insert values in a list with the insert() method. Here, you specify a value to insert at a specific position.
>>> nums=[1,2,3] >>> nums.insert(2,4) >>> nums
Output:
3. extend()
extend() can add multiple items to a list.
Learn by example:
>>> nums=[1,2,3] >>> nums.extend([[4,5,6],(7,8),9]) >>> nums
Output:
Deleting Elements in Python Lists
Lists have methods for deleting elements. They are remove() and pop() and are slightly different from each other.
>>> nums=[1,2,3,2,4,5,3,6,7,8] >>> nums.remove(2) >>> nums
Output:
>>> nums.pop()
Output:
>>> nums.pop()
Output:
Here in this example, we say we want to remove the value 2 from this list.
It removes the first occurrence of 2 at index 1 but does not remove the second one at index 3. By default, pop() removes the last element in the list. You cannot remove an element that is not in the list.
>>> nums.remove(0)
Output:
File “<pyshell#148>”, line 1, in <module>
nums.remove(0)
ValueError: list.remove(x): x not in list
We can also give pop() and index to make it remove an element from a specific index.
>>> nums
Output:
>>> nums.pop(5)
Output:
>>> nums
Output:
Looping on Lists in Python
Since lists are collections of elements, we can use them in for-loops. You can do this if you want to do something for every value in a list.
Code:
for num in [1,2,3,4,5,6]: print(num)
Output:
2
3
4
5
6
Code:
nums=[1,2,3,4,5,6] for index in range(len(nums)): print(nums[index])
Output:
2
3
4
5
6
Python Lists Length
Like for strings, we can calculate the length of a list. For this, we use the in-built len() function.
>>> nums=[1,2,3,4,5] >>> len(nums)
Output:
for index in range(len(nums)): print(index,nums[index])
Output:
1 2
2 3
3 4
4 5
Concatenating, Repetition and Membership
We can join two lists with the + operator. It adds integers and floats but concatenates strings and lists.
>>> [1,2,3]+[4,5]+[6]
Output:
We can make a list repeat by multiplying it by an integer. We saw this in strings.
>>> [1,2,3]*3
Output:
And we can also check whether a value is in a list. For this, we use the in operator.
>>> [1,2] in [1,2,3]
Output:
>>> 2 in [1,2,3]
Output:
>>> '' not in []
Output:
Copying Lists in Python
The list class has an in-built copy() method which creates a copy of a list.
>>> nums=[1,2,3,4] >>> nums1=nums.copy() >>> nums1
Output:
nums1 is a shallow copy of nums. If we change a value in nums1, it will not affect nums.
>>> nums1[2]=7 >>> nums
Output:
Nested Lists and Comprehension
Lists are heterogeneous collections and we can make lists hold lists.
>>> nums=[1,2,3,[4,[5,6,7],8,[9,10]]]
Now let’s talk about list comprehension.
This is a shortcut to create a list.
>>> nums=[num for num in range(1,8)] >>> nums
Output:
Here, for each number from 1 to 7, we add it to the list nums.
>>> nums=[num**2 for num in range(1,8)] >>> nums
Output:
And this is a list of squares of numbers from 1 to 7.
You can add if-conditions to a list comprehension:
>>> nums=[num for num in range(1,8) if num%2==0] >>> nums
Output:
1. Nested List Comprehension
You cannot convert all nested loops to list comprehension, but when you can:
>>> nums=[[num for num in range(1,8)] for val in [2,3,4]] >>> nums
Output:
Methods on Lists in Python
Like we said before, we have in-built methods for lists.
Let’s call them.
1. append()
This appends a single value to the end of a list.
>>> nums=[1,2,3,4,5] >>> nums.append(6) >>> nums
Output:
2. extend()
This adds the elements of a list to another list.
>>> nums=[1,2,3,4,5] >>> nums.extend([3,4,[5,6],7]) >>> nums
Output:
3. insert()
This inserts an element at a specified index.
>>> nums=[1,2,3,4,5] >>> nums.insert(6,6) >>> nums
Output:
4. remove()
This removes the specified item from the list.
>>> nums=[1,2,3,4,5] >>> nums.remove(4) >>> nums
Output:
5. pop()
This removes and returns an element at the specified index.
>>> nums=[1,2,3,4,5] >>> nums.pop(3)
Output:
>>> nums.pop()
Output:
6. clear()
This removes all items from the list.
>>> nums=[1,2,3,4,5] >>> nums.clear() >>> nums
Output:
7. index()
This returns the index of the first match of an item.
>>> nums=[1,2,3,2,5] >>> nums.index(2)
Output:
8. count()
This returns the number of occurrences of the specified item in a list.
>>> nums=[1,2,3,2,5] >>> nums.count(2)
Output:
9. sort()
This sorts the list in ascending order.
>>> nums=[2,1,5,3,2] >>> nums.sort() >>> nums
Output:
>>> nums.sort(reverse=True) >>> nums
Output:
10. reverse()
This reverses a list.
>>> nums=[1,2,3,4,5] >>> nums.reverse() >>> nums
Output:
sort() and reverse() change the original list.
11. copy()
This returns a shallow copy of a list.
>>> nums=[1,2,3] >>> nums1=nums.copy() >>> nums1
Output:
Python List Functions
Methods can change the list, but functions will operate on a list and return a value. Python has some in-built functions for lists.
1. all()
This returns True if all elements in the list are True or if the list is empty.
>>> all([1,2,False])
Output:
2. any()
This returns True if at least one element in the list is True or if the list is not empty.
>>> all([1,2,False])
Output:
>>> any([1,2,False])
Output:
3. enumerate()
This returns an enumerate object for the list. It gives the list items with their indices.
>>> for pair in enumerate([1,2,3]): print(pair)
Output:
(1, 2)
(2, 3)
4. filter()
filter() takes a function and filters a sequence by checking each item.
>>> list(filter(lambda val:val%2==0, [1,2,3,4,5,6,7,8,9]))
Output:
5. len
This returns the length of the list.
>>> len([1,2,[3,[5,4],6]])
Output:
This list’s length is 3, not 6, it has sublists.
Summary
And with this, we are done with lists in Python.
In this article, we talked about Python lists, how to create them, index them, slice them, modify them, add elements, delete elements.
Also, we have learned loop on lists, get their lengths, concatenate, repeat, check membership, copy them, nested lists and comprehension, methods on lists and some in-built functions.