Python Lists – Learn to store multiple values in Python

Hope you had fun learning about data structures. Now let’s learn about Python lists. Like data structures, we will learn how to deal with 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:

Code:

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:

Code:

>>> items=[1,2,3]
>>> items

Output:

[1, 2, 3]

Code:

>>> items=list('123')
>>> items

Output:

[‘1’, ‘2’, ‘3’]

Code:

>>> items=['123']
>>> items

Output:

[‘123’]

Code:

>>> items=[]
>>> items.append(7)
>>> items

Output:

[7]

Code:

>>> items=[1, 2, False, [4, 5]]
>>> items

Output:

[1, 2, False, [4, 5]]

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.

Code:

>>> values

Output:

[‘milk’, ‘cheese’, 12, False]

Code:

>>> values[2]

Output:

12

12 is the value at index 2.

1. Positive Indexing

Indexing left to right, starts at 0.

Code:

>>> values[1]

Output:

‘cheese’

2. Negative Indexing

Indexing right to left, starts at -1.

Code:

>>> values[-1]

Output:

False

Slicing Lists in Python

We can slice lists as well. This gives us only a part of the list. Read slicing strings if you don’t remember. Slicing can take one, two or three values – start, stop and step. Let’s take examples here as well.

Code:

>>> values #list

Output:

[‘milk’, ‘cheese’, 12, False]

Code:

>>> values[:] #complete list

Output:

[‘milk’, ‘cheese’, 12, False]

Code:

>>> values[:2] #upto index 1

Output:

[‘milk’, ‘cheese’]

Code:

>>> values[2:] #from index 2 to end

Output:

[12, False]

Code:

>>> values[-3:] #from index -3 to end

Output:

[‘cheese’, 12, False]

Code:

>>> values[1::2] #from index 1 to end with a step of 2

Output:

[‘cheese’, False]

Modifying Lists in Python

Unlike strings, lists are mutable. You can change its values. Let us take a few examples.

Code:

>>> values

Output:

[‘milk’, ‘cheese’, 12, False]

Code:

>>> values[1]='bread'
>>> values

Output:

[‘milk’, ‘bread’, 12, False]

values[1] is now ‘bread’ and not ‘cheese’.

Code:

>>> values[1:1]=['cheese','eggs']
>>> values

Output:

[‘milk’, ‘cheese’, ‘eggs’, ‘bread’, 12, False]

If we assign this list to the slice values[1:1], it adds the values ‘cheese’ and ‘eggs’ between indices 0 and 1.

Now, in Python lists article, let’s see how to add and delete elements in it.

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.

Code:

>>> nums=[1,2,3]
>>> nums.append(4)
>>> nums.append([5,6])
>>> nums.append((7,8))
>>> nums

Output:

[1, 2, 3, 4, [5, 6], (7, 8)]

2. insert()

You can insert values in a list with the insert() method. Here, you specify a value to insert at a specific position.

Code:

>>> nums=[1,2,3]
>>> nums.insert(2,4)
>>> nums

Output:

[1, 2, 4, 3]

3. extend()

extend() can add multiple items to a list. Learn by example:

Code:

>>> nums=[1,2,3]
>>> nums.extend([[4,5,6],(7,8),9])
>>> nums

Output:

[1, 2, 3, [4, 5, 6], (7, 8), 9]

Deleting Elements in Python Lists

Lists have methods for deleting elements. They are remove() and pop() and are slightly different from each other.

Code:

>>> nums=[1,2,3,2,4,5,3,6,7,8]
>>> nums.remove(2)
>>> nums

Output:

[1, 3, 2, 4, 5, 3, 6, 7, 8]

Code:

>>> nums.pop()

Output:

8

Code:

>>> nums.pop()

Output:

7

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.

Code:

>>> nums.remove(0)

Output:

Traceback (most recent call last):
  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.

Code:

>>> nums

Output:

[1, 3, 2, 4, 5, 3, 6]

Code:

>>> nums.pop(5)

Output:

3

Code:

>>> nums

Output:

[1, 3, 2, 4, 5, 6]

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:

1
2
3
4
5
6

Code:

nums=[1,2,3,4,5,6]
for index in range(len(nums)):
    print(nums[index])

Output:

1
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.

Code:

>>> nums=[1,2,3,4,5]
>>> len(nums)

Output:

5

Code:

for index in range(len(nums)):
    print(index,nums[index])

Output:

0 1
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.

Code:

>>> [1,2,3]+[4,5]+[6]

Output:

[1, 2, 3, 4, 5, 6]

We can make a list repeat by multiplying it by an integer. We saw this in strings.

Code:

>>> [1,2,3]*3

Output:

[1, 2, 3, 1, 2, 3, 1, 2, 3]

And we can also check whether a value is in a list. For this, we use the in operator.

Code:

>>> [1,2] in [1,2,3]

Output:

False

Code:

>>> 2 in [1,2,3]

Output:

True

Code:

>>> '' not in []

Output:

True

Copying Lists in Python

The list class has an in-built copy() method which creates a copy of a list.

Code:

>>> nums=[1,2,3,4]
>>> nums1=nums.copy()
>>> nums1

Output:

[1, 2, 3, 4]

nums1 is a shallow copy of nums. If we change a value in nums1, it will not affect nums.

Code:

>>> nums1[2]=7
>>> nums

Output:

[1, 2, 3, 4]

Nested Lists and Comprehension

Lists are heterogeneous collections and we can make lists hold lists.

Code:

>>> 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.

Code:

>>> nums=[num for num in range(1,8)]
>>> nums

Output:

[1, 2, 3, 4, 5, 6, 7]

Here, for each number from 1 to 7, we add it to the list nums.

Code:

>>> nums=[num**2 for num in range(1,8)]
>>> nums

Output:

[1, 4, 9, 16, 25, 36, 49]

And this is a list of squares of numbers from 1 to 7.

You can add if-conditions to a list comprehension:

Code:

>>> nums=[num for num in range(1,8) if num%2==0]
>>> nums

Output:

[2, 4, 6]

1. Nested List Comprehension

You cannot convert all nested loops to list comprehension, but when you can:

Code:

>>> nums=[[num for num in range(1,8)] for val in [2,3,4]]
>>> nums

Output:

[[1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7]]

Next in Python lists article, explore the built-in methods for lists.

Methods on Lists in Pythonpython list methods

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.

Code:

>>> nums=[1,2,3,4,5]
>>> nums.append(6)
>>> nums

Output:

[1, 2, 3, 4, 5, 6]

2. extend()

This adds the elements of a list to another list.

Code:

>>> nums=[1,2,3,4,5]
>>> nums.extend([3,4,[5,6],7])
>>> nums

Output:

[1, 2, 3, 4, 5, 3, 4, [5, 6], 7]

3. insert()

This inserts an element at a specified index.

Code:

>>> nums=[1,2,3,4,5]
>>> nums.insert(6,6)
>>> nums

Output:

[1, 2, 3, 4, 5, 6]

4. remove()

This removes the specified item from the list.

Code:

>>> nums=[1,2,3,4,5]
>>> nums.remove(4)
>>> nums

Output:

[1, 2, 3, 5]

5. pop()

This removes and returns an element at the specified index.

Code:

>>> nums=[1,2,3,4,5]
>>> nums.pop(3)

Output:

4

Code:

>>> nums.pop()

Output:

5

6. clear()

This removes all items from the list.

Code:

>>> nums=[1,2,3,4,5]
>>> nums.clear()
>>> nums

Output:

[]

7. index()

This returns the index of the first match of an item.

Code:

>>> nums=[1,2,3,2,5]
>>> nums.index(2)

Output:

1

8. count()

This returns the number of occurrences of the specified item in a list.

Code:

>>> nums=[1,2,3,2,5]
>>> nums.count(2)

Output:

2

9. sort()

This sorts the list in ascending order.

Code:

>>> nums=[2,1,5,3,2]
>>> nums.sort()
>>> nums

Output:

[1, 2, 2, 3, 5]

Code:

>>> nums.sort(reverse=True)
>>> nums

Output:

[5, 3, 2, 2, 1]

10. reverse()

This reverses a list.

Code:

>>> nums=[1,2,3,4,5]
>>> nums.reverse()
>>> nums

Output:

[5, 4, 3, 2, 1]

sort() and reverse() change the original list.

11. copy()

This returns a shallow copy of a list.

Code:

>>> nums=[1,2,3]
>>> nums1=nums.copy()
>>> nums1

Output:

[1, 2, 3]

Python List Functionsfunctions in python list

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.

Code:

>>> all([1,2,False])

Output:

False

2. any()

This returns True if at least one element in the list is True or if the list is not empty.

Code:

>>> all([1,2,False])

Output:

False

Code:

>>> any([1,2,False])

Output:

True

3. enumerate()

This returns an enumerate object for the list. It gives the list items with their indices.

Code:

>>> for pair in enumerate([1,2,3]): print(pair)

Output:

(0, 1)
(1, 2)
(2, 3)

4. filter()

filter() takes a function and filters a sequence by checking each item.

Code:

>>> list(filter(lambda val:val%2==0, [1,2,3,4,5,6,7,8,9]))

Output:

[2, 4, 6, 8]

5. len

This returns the length of the list.

Code:

>>> len([1,2,[3,[5,4],6]])

Output:

3

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.

If you have any queries in Python lists article, mention them in the comment section. TechVidvan’s team will be happy to help you.

Happy Learning!!

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.