Python Lists

In Python, a list is an ordered sequence of items. Python lists are one of the 4 data types used to store collections of data.

(multiple items in a single variable)

The 4 data types that store collections are: dictionaries, lists, sets and tuples, which we’ll cover in other lessons.


Subscribe to my Newsletter


Creating a List in Python

Lists are created using square brackets ([])

# Example
ls = [1, 2, 3]
ls

In the output, we know that the element is a list based on the square brackets.

[1, 2, 3]

Storing Different Data Types Inside Lists

Lists of Strings

# strings
ls = ['python','seo']
ls
['python', 'seo']

Lists of Booleans

# Booleans
ls = [False, True, True]
ls
[False, True, True]

Lists of Lists (Nested Lists)

We can store lists within lists. Those are referred to as nested lists.

# nested lists
ls = [
    [1,2,3],
    [4,5,6]
]
ls
[[1, 2, 3], [4, 5, 6]]

Lists of Tuples

# tuples
ls = [
    (0, 1),
    (2, 3),
    (4, 5)
]

ls
[(0, 1), (2, 3), (4, 5)]

Lists of Dictionaries

# dicts
ls = [
    {'a': 1},
    {'b': 2}
]
ls
[{'a': 1}, {'b': 2}]

Lists with Different Data Types Mixed

# mixed items
ls = ['hello', 1, True, [1, 2]]
ls
['hello', 1, True, [1, 2]]

List Indexing in Python

Let’s talk about indexing list. You can access items of a list using its index.

Each element of a list has its own integer attributed to.

Get the First Element of a List in Python

Python uses zero-based indexing, so if you want to get the first element, then you need to use the square brackets on the list variable with the value of zero.

# Get first element of list
ls = [1, 2, 3]
ls[0]
1

Get the Last Element of a List in Python

If you want to get the last element of a list then you need to use the same square brackets notation on the variable. But this time, instead of using the value of zero, we use the -1 value, which tells you this is the last value of the list.

# Get last element of list
ls = [1, 2, 3]
ls[-1]
3

Get a Range of Values Within a List

If we want to subset more than one value then we will need to use list ranges. Again, use the square brackets on the variable and then we start from the first index to include up to the last index [start:end]. Note that the end value is not included in the range subsetting.

# List range
ls = [0, 1, 2, 3, 4, 5]
ls[1:3]
[1, 2]

List Range from the Start Up to an Index

If you don’t add a value before the colon in the brackets, then it is implied that you want all the values from the start.

# List from start
ls = [0, 1, 2, 3, 4, 5]
ls[:3]
[0, 1, 2]

List Range from an Index Up to the End

If you don’t add a value after the colon in the brackets, then it is implied that you want all the values after the starting index up until the end.

# List range to end
ls = [0, 1, 2, 3, 4, 5]
ls[1:]
[1, 2, 3, 4, 5]

Modifying Lists in Python

Change a Single Value within a Python List

To change a single value within a list in Python, you can use the square brackets with the index of the value that you want to change. Then, reassign its value using the equal sign. The new value doesn’t have to be of the same data type.

# Change a single value
ls = [0, 1, 2, 3, 4, 5]
ls[1] = 'new value'
ls
[0, 'new value', 2, 3, 4, 5]

Change Multiple Values within a Python List

To change multiple values within a list in Python, you can use the square brackets with an index range for the values that you want to change. Then, reassign its value using the equal sign. The new values don’t have to be of the same data type.

# Change multiple values
ls = [0, 1, 2, 3, 4, 5]
ls[1:3] = ['new', False]
ls
[0, 'new', False, 3, 4, 5]

Changing the Values, But add More

If you decide to reassign new values, but intentionally or accidentally add more values that the selected index, then values will be added to the end of the list.

# Adding more
ls = [1, 2, 3]
ls[-1:] = [4, 5, 6]
ls
[1, 2, 4, 5, 6]

Adding Items to a List in Python

There are multiple ways to add items to a Python list: appending, extending and inserting.

Appending to a List

You can use the append() method to add items to a list.

# Append
ls = []

ls.append('a')
ls
['a']

Pitfall of List Append

If you want to combine two lists together, using the append() method would append the entire list inside the existing list. So, the list would be only one of the items.

# Pitfall of append
ls = [1, 2, 3]
ls2 = [4, 5, 6]

ls.append(ls2)
ls
[1, 2, 3, [4, 5, 6]]

Extending a Python List

To combine two lists together in Python, you can use the extend() method.

# Extend
ls = [1, 2, 3]
ls2 = [4, 5, 6]

ls.extend(ls2)
ls
[1, 2, 3, 4, 5, 6]

Inserting an Item at a Specific Position in a List

To insert an element at a specific position in a list, use the Python insert() method where the first argument is the position and the second argument is the value to be inserted.

# insert in specific position
ls = [1, 3, 4]
ls.insert(1, 2)
ls
[1, 2, 3, 4]

Removing Items From a List in Python

List Remove()

To remove a value from Python list, use the remove() method where the argument is the value to be removed.

# Remove
ls = ['a', 'b', 'c']
ls.remove('a')
ls
['b', 'c']

List pop()

To remove a value from Python list using its index, use the pop() method where the argument is the index of the value to be removed. By default, the pop() method will remove the last value.

# Remove with index pop()
# Default remove last index
ls = ['a', 'b', 'c']
ls.pop(2)
ls
['a', 'b']

Deleting a Value

You can also remove a value from Python list using its index by using the del keyword.

# Remove with index: del
ls = ['a', 'b', 'c']
del ls[1]
ls
['a', 'c']

The main difference with pop() is that pop() can store the value that is removed within a variable while del simply removes it..

# Remove with index pop()
# Default remove last index
ls = ['a', 'b', 'c']
x = ls.pop(2)
x
'c'

Clear all Values from the List

Use the clear() method to clear the list from all its values.

# clear
ls = [1, 2, 3]
ls.clear()
ls
[]

Creating Lists in Python

You can create a list in multiple ways in Python: use the square brackets, use a list constructor, use a list comprehension.

Creating Lists with the Square Brackets

You can create a list using the square brackets.

# creating a list
a = [1,2,3]
type(a)
list

Creating Lists Using the list Constructor

You can also create a list using the list() constructor.

# constructor
t = (1, 2, 3)
list(t)
[1, 2, 3]

Creating Lists Using a list Comprehension

You can also create a list using a list comprehension.

# list comprehension
ls = [i for i in range(10)]
ls
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Looping Through a List in Python

Looping can be used on Python lists.

Looping Through all the Values of a List

You can loop through all the values inside of a list by using a for loop.

# Looping
ls = [
    'python',
    'machine learning',
    'seo',
    'programming',
    'computer science'
]

for elem in ls:
    print(elem)
python
machine learning
seo
programming
computer science

Looping Through all the Values of a List using the Index

To loop through the values of a list using the indexes. Create a for loop with the range() function.

Here, I use a lot of printing to show up what the loop actually does.

# Looping with index
ls = [
    'python',
    'machine learning',
    'seo',
    'programming',
    'computer science'
]

# Print List info
print('list length:', len(ls))
print('list range:', range(len(ls)))

# Loop each index in the list
print('starting loop')
for i in range(len(ls)):
    print('list index is:', i)
    print('list item is:', ls[i])
list length: 5
list range: range(0, 5)
starting loop
list index is: 0
list item is: python
list index is: 1
list item is: machine learning
list index is: 2
list item is: seo
list index is: 3
list item is: programming
list index is: 4
list item is: computer science

Looping Through a List Using a While Loop

You can loop through all the values inside of a list by using a while loop.

# while 
ls = [
    'python',
    'machine learning',
    'seo',
    'programming',
    'computer science'
]

# Define start point
i = 0 

# Until this condition is met
while i < len(ls):
    # Print
    print('list index is:', i)
    print('list item is:', ls[i])
    # Increment i
    i += 1
list index is: 0
list item is: python
list index is: 1
list item is: machine learning
list index is: 2
list item is: seo
list index is: 3
list item is: programming
list index is: 4
list item is: computer science

Looping Through a List Using a List Comprehension

You can loop through all the values inside of a list by using a list comprehension.

# Loop with List comprehension
ls = [
    'python',
    'machine learning',
    'seo',
    'programming',
    'computer science'
]

# List comprehension
[print(elem) for elem in ls]
python
machine learning
seo
programming
computer science
[None, None, None, None, None]

Searching in Lists with Python

You can search through element of a list using the combination of a loop and of the if statement.


element found

Sorting Python Lists

To sort elements of a list in Python, use the sort() method.

For sort to work, all values of the lists need to be of the same data type.

Sorting a List of Strings

# sort()
ls = ['hello','world','sort','this','list']
ls.sort()
ls
['hello', 'list', 'sort', 'this', 'world']

Sorting a List of Integers

# sort()
ls = [0,3,5,15,6,8,2,6,8]
ls.sort()
ls
[0, 2, 3, 5, 6, 6, 8, 8, 15]

Reverse Sorting a List in Python

To reverse sort a list in python, use the reverse parameter.

# reverse sort
ls.sort(reverse = True)

Joining Python Lists Together

# Join two lists
ls1 = ['a','b','c']
ls2 = [1,2,3]

ls1 + ls2
['a', 'b', 'c', 1, 2, 3]
# Similar but different to 
ls1.extend(ls2)
ls1
['a', 'b', 'c', 1, 2, 3]

Conclusion

This was a very simple introduction to Python Lists.

Enjoyed This Post?