An Extensive Guide to Python Lists

Nibesh Khadka
12 min readApr 22, 2021
Python Lists-Practce

This article on lists in Python is the continuation of a tutorial series on the Python programming language for beginners. This tutorial is all about lists. I wrote a previous article about Python numbers. You can also find a full list of exercises here.

Intro

List is one of the built-in data types that’s meant to store data in sequence or collection.

Some features that make list a repeated object in your codes are:

  1. It preserves the order of data stored.
  2. Easy to manipulate. Comes with many methods as we’ll see later.
  3. They are mutable since they can be changed.

Creating a List

A list can be created in two ways.

  1. list([1,12,’34’])
  2. [1,12,’34’]

The first method seems like a hassle but it comes in handy when we have to convert other data types to a list. For example, the conversion of NumPy array to a list.

my_favorite_fruits = ['apple','banana', 'peach','persimmon']my_favourite_apps=list(['audible','youtube', 'medium', 'messenger'])print("My favorite fruits are: "my_favorite_fruits)print("My favorite apps are : "my_favourite_apps)

Output:

My favorite fruits are:  ['apple', 'banana', 'peach', 'persimmon'] My favorite apps are :  ['audible', 'youtube', 'medium', 'messenger']

Index

Index means the position in a list but it is not exactly the same as an ordinary count. In Python, the index starts from zero(0), not one(1). This is the same for other data types like strings and the logic is similar to other programming languages.

Let’s not get confused, and check out the code. In Python, we can find the index of an item in a list with the index() function.

# Indexingvowel_letters=['a','e','i','o','u']#Print the listprint(vowel_letters)#Print the length of listprint("Length of vowel_letters is {}".format(len(vowel_letters)))#Print the position of itemsprint("Position of 'a' is {} in vowel_letter.".format(vowel_letters.index('a')))print("Position of 'u' is {} in vowel_letter.".format(vowel_letters.index('u')))

Output:

['a', 'e', 'i', 'o', 'u'] Length of vowel_letters is 5 Position of 'a' is 0 in vowel_letter. 
Position of 'u' is 4 in vowel_letter.

Check the output. Even though the length of the list is 5, the first item has an index of 0 and the last of 4. Hence, whenever you want to find the index of an item from a list, just subtract one from your count.

Accessing Items

Now that we know about the list index, let’s access them. A list item can be accessed as: For one item: list_name[index].

# Accessing Items in listodd_numbers =[1,3,5,7,9]even_numbers=[2,4,6,8,10]  #Print listprint("Odd numbers: ",odd_numbers)print("Even numbers: ",even_numbers)# Accessing item in the list.print("First item in the odd_numbers is", odd_numbers[0])print("Second item in the even_numbers is", even_numbers[1])

Output:

Odd numbers:  [1, 3, 5, 7, 9] 
Even numbers: [2, 4, 6, 8, 10]
First item in the odd_numbers is 1
Second item in the even_numbers is 4

Slicing

In a list, accessing multiple items is done by slicing. The syntax for slicing is:

list_name[start: stop: step], where

  1. Start is the index of the element where you want to start slicing from. It's optional, and starts from 0 if no value is given.
  2. Stop is the the index of element before which you want to stop slicing. What I mean by before is that it's exclusive, not included in the sliced list. Also stop is also optional and ends till the last item in the list, if no value is given.
  3. Step is the number of jumps on each slice, it's also optional.
# Create odd numbers less than 100#use list comprehensionodd_number_less_100 = [i for i in range(0, 100) if (i % 2 != 0)]#Print the odd Numbersprint(odd_number_less_100)#Print new line to create gapprint("\n")# Slicing the itemsprint("First 10 items in the list: ",odd_number_less_100[:10])print("\n")#Adding - before index means count from last and backwards.print("Last 10 items in the list: ",odd_number_less_100[-10:])

Output:

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99] First 10 items in the list:  [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]   Last 10 items in the list:  [81, 83, 85, 87, 89, 91, 93, 95, 97, 99]

Mixed indexing:

# Slice Using Start and stopprint("Items from index 10th and 30th index in the list: ",odd_number_less_100[10:30])# Slice using start and stepprint("Items starting from 5th index with +10 jump: ",odd_number_less_100[5::10])print("\n")#slice using stop and stepsprint("Items with the jump of 5 until the index of 40 ",odd_number_less_100[:40:5])# Slice with only jumps or stepsprint("\n")print("All the items 6 steps apart: ",odd_number_less_100[::6])

Output:

Items from index 10th and 30th index in the list:  [21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59] Items starting from 5th index with +10 jump:  [11, 31, 51, 71, 91]   Items with the jump of 5 until the index of 40  [1, 11, 21, 31, 41, 51, 61, 71]  All the items 6 steps apart:  [1, 13, 25, 37, 49, 61, 73, 85, 97]

Hope I covered every variation of example possible.

Methods In List

Copy()

Copy is a very important method on the list object. As the name suggests, it creates a new copy of the given list object. Copy comes handy when we want to tweak a list but still want to preserve the original list. So, we make a copy of the list and play with it.

Syntax: list.copy()

# Create list for copy.clrs_in_rainbow =['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']print("Colors in rainbow: ", clrs_in_rainbow)# create a copyclrs_in_rainbow_cpy_1 = clrs_in_rainbow.copy()print("Copy of colors in rainbow: ", clrs_in_rainbow_cpy_1)

Output:

Colors in rainbow:  ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']

Copy of colors in rainbow: ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']

Insert()

Insert is one of the methods to add items to the list. The special thing about insert is you can choose the index where you would want to insert the item in.

One thing to remember is that it happens in place, i.e it changes the original list. So, better to make a copy if you want to preserve the original list. One of the cases where preservation can be really important is when you are using the order of the list in your database and then you go on and mess it up using insert. Hence, use copy first.

Syntax: list.insert(index, item), where

  1. Index is the index of the item in your list before which you want to insert a new item.
  2. Item is the new value you want to add.
# List of even numbers from 10 to 20even_number_frm_10_20= [i for i in range(10,21) if i%2==0]#Print the listprint("Even numbers from 10 to 20: ",even_number_frm_10_20)#Create new copy before inserting using copy()extended_list = even_number_frm_10_20.copy()extended_list.insert(0,8)#Print the list after insertionprint("\n")print("Even numbers after inserting 8: ",even_number_frm_10_20, "is preserved due to copy.")print("\n")print("Extended new list after inserting 8: ",extended_list)# Insert after  last itemextended_list.insert(len(extended_list),22)print("Extended new list after inserting 22: ",extended_list)

Output:

Even numbers from 10 to 20:  [10, 12, 14, 16, 18, 20]Even numbers after inserting 8:  [10, 12, 14, 16, 18, 20] is preserved due to copy.   Extended new list after inserting 8:  [8, 10, 12, 14, 16, 18, 20]  Extended new list after inserting 22:  [8, 10, 12, 14, 16, 18, 20, 22]

Append

The append method aids to add items to the end of the list. It is similar to using the insert() method when you want to enter an item at the end: list.insert(len(list), new_item).

Syntax: list.append(item)

# Append topic# Create new listanimals_in_africa =['elephant','lion','zebra']print("Original Animals in Africa list: ",animals_in_africa)animals_in_africa.append('hyena')print("Animals in Africa list after append: ",animals_in_africa)

Output:

Original Animals in Africa list:  ['elephant', 'lion', 'zebra'] Animals in Africa list after append:  ['elephant', 'lion', 'zebra', 'hyena']

Again make a copy if there’s need be.

Insert Vs. Append

The insert method can help to add items anywhere. The only drawback is you have to know the index, so coding can get complicated depending on the situation.

Append can only add items to the end of the list. It’s very simple and easy but you have to control the index of the item to be added.

Remove

Just like adding items, there are methods to remove them. Remove helps remove the first matching item from the list. It does not return any value, just removes one from the original list.

Syntax: list.remove(item)

# Remove Topic#Create list
vegges = ['onion','carrots','okra', 'potato']
#print
print("Vegges before:",vegges)
#Lets remove carrots from the list
vegges.remove('carrots')
print("Vegges After:",vegges)

Output:

Vegges before: ['onion', 'carrots', 'okra', 'potato'] Vegges After: ['onion', 'okra', 'potato']

Pop

After remove, another method to remove items from the list is pop. But it only removes the item at the end of the list.

Syntax: list.pop(item)

#Pop Topic
#Create list of flowers
flowers=list(['marigold', 'jasmine','rose','lotus','sunflower'])
#Print the list
print("Flowers before: ", flowers )
#Use pop
flowers.pop()
print("Flowers after: ", flowers )

Output

Flowers before:  ['marigold', 'jasmine', 'rose', 'lotus', 'sunflower'] Flowers after:  ['marigold', 'jasmine', 'rose', 'lotus']

Remove vs. Pop

Remove can delete any items from the list. However, it only deletes the first matching item. Also, you have to know the content of the list beforehand.

Pop offers fewer options and only removes the last item. However, you do not necessarily have to know the content.

Count

If you want to find out the number of occurrences of an item in a list then use count.

Syntax: list.count(x)

# Count topic
vowel_letters= ["a",'e','i','o','u']*3
#print the list
print("Three times the vowel letter list: ", vowel_letters)
# Lets Find out the count of o
print("The letter 'o' is repeated {} times in the list.".format(vowel_letters.count('o')))

Output:

Three times the vowel letter list:  ['a', 'e', 'i', 'o', 'u', 'a', 'e', 'i', 'o', 'u', 'a', 'e', 'i', 'o', 'u']The letter 'o' is repeated 3 times in the list.

Sort

The sort method is similar to the built-in sorted method in Python. It can help sort a list in ascending or descending order. It modifies the list but does not return anything.

Syntax: list.sort(*,key=None,reverse=False)

  1. * mean all the items in the list.
  2. Key can be used to modify the behavior of the sort.
  3. reverse determines the order, the default value is False, whereas True returns descending order.

The value of each parameter is the default one.

# Sort
random_evens =[24,6,92,10,500,2,82]
#Print the list
print("The original list: ", random_evens)
#Sort without key
print(random_evens.sort())
print("After random list:," ,random_evens)

Output:

The original list:  [24, 6, 92, 10, 500, 2, 82] NoneAfter random list:, [2, 6, 10, 24, 82, 92, 500]

You are not mistaken, you did see ‘None’ in the second output line. It's happening because as I mentioned earlier, sort modifies the list but does not return anything. When a function does not return anything, then by default ‘None’ is returned. It's a programming character. A ‘None’ is a data type in Python meaning nothing.

Let's explore sort further.

random_evens = [24, 6, 92, 10, 500, 2, 82]
print("The original list: ", random_evens)
# Lets make key:value pair with item dictionary
# Content will be random_even items and the reminder when they are #divided by 5.
random_even_modulars = {item: item % 5 for item in random_evens}
print("Reminders after random_even divided by 5:", random_even_modulars)

Output:

The original list:  [24, 6, 92, 10, 500, 2, 82] Reminders after random_even divided by 5: {24: 4, 6: 1, 92: 2, 10: 0, 500: 0, 2: 2, 82: 2}

Why am I doing this?

First of all, don’t worry about that complicated dictionary creation, we can take about it later on. The main thing to notice here is the key and its value, and we are going to sort the list items according to the values we got from the division operation.

random_evens = [24, 6, 92, 10, 500, 2, 82]
print("The original list: ", random_evens)
random_even_modulars = {item: item % 5 for item in random_evens}
print("Reminders after random_even divided by 5:", random_even_modulars)
print("The original list: ", random_evens)
print("Reminders after random_even divided by 5:", random_even_modulars)
# Create new copy
new_list = random_evens.copy()
#Sort by key
new_list.sort(key=lambda i:i%5)
print("The new list sorted by key is",new_list)

Output:

The original list:  [24, 6, 92, 10, 500, 2, 82]

Reminders after random_even divided by 5: {24: 4, 6: 1, 92: 2, 10: 0, 500: 0, 2: 2, 82: 2}

The new list sorted by key is [10, 500, 6, 92, 2, 82, 24]

See the change? The list is still ordered in ascending order but this not by the item itself but the logic in the key attribute. If not sure, compare to the dictionary values and see which one should be sorted first.

And don’t worry about lambda. It's a way to write anonymous functions for one-time use.

Reverse

It reverses the items in the list. It's not the same as sort (reverse=True) because sort orders items by some form of comparison. However, reverse just re-orders the list from last to first without comparing.

Syntax: list.reverse()

# Reverse
palindrom_string = 'madam'
palindrom_lst =list(palindrom_string)
print("Original Palindrome string:", palindrom_string)
print("List of letters in Palindrome sting: ",palindrom_lst)
# Now lets verify if the letter are actually palindrom
palindrom_lst_reverse = palindrom_lst.copy()
palindrom_lst_reverse.reverse()
#Join the srting again
reversed_palindrom_str = "".join(palindrom_lst_reverse)
#Print
print("Palindrome list after reversed:", palindrom_lst_reverse)
print("Palindrome string after reversed:", reversed_palindrom_str)

Output

Original Palindrome string: madamList of letters in Palindrome sting:  ['m', 'a', 'd', 'a', 'm']Palindrome list after reversed: ['m', 'a', 'd', 'a', 'm']Palindrome string after reversed: madam

Palindromes are words that are at the same time spelled backward. In this code block, we not only reversed a list but also used other techniques like string–> list conversion, list –> string conversion by join. Moreover, we also did a palindrome verification problem.

So, these were some methods that are available in the list. Now, let's see how the list is used in combination with other methods.

For and List

For is a looping technique in Python. I will write a separate article on loops. For is used to create, loop over, and modify a list.

# Create new list
saarc_countries =['Afghanistan', 'Bangladesh', 'Bhutan', 'India', 'the Maldives', 'Nepal', 'Pakistan','Sri Lanka']
# Lets loop over each countries and print them on the screen
for country in saarc_countries:
print(country)

Output:

Afghanistan 
bangladesh
bhutan
India
the maldives
Nepal
Pakistan
Sri Lanka

As you’ve noticed, some countries have lowercase initials. Let’s change them to upper case.

# Create new list
saarc_countries =['Afghanistan', 'bangladesh', 'bhutan', 'India', 'the maldives', 'Nepal', 'Pakistan','Sri Lanka']
print("List before modification:", saarc_countries)# Lets loop over each countries
# access each item to modify using range and list index
for i in range(len(saarc_countries)):
# use str.title() method to change initials to uppercase.
saarc_countries[i] = saarc_countries[i].title()
print("List after modification:", saarc_countries)

Output:

List before modification: ['Afghanistan', 'bangladesh', 'bhutan', 'India', 'the maldives', 'Nepal', 'Pakistan', 'Sri Lanka']List after modification: ['Afghanistan', 'Bangladesh', 'Bhutan', 'India', 'The Maldives', 'Nepal', 'Pakistan', 'Sri Lanka']

This is how we use lists together with for loops.

List Comprehensions

If you’ve read the article from the beginning you’ve already noticed how I’ve been creating lists using list comprehensions. It basically does in one line the for loop part for list creation we saw in the preceding code block.

# List Comprehension
# first create empty list
even_numbers_less_50 = []
# Use for loop to creae list of even numbers
for i in range(50):
if (i % 2 == 0):
even_numbers_less_50.append(i)
# Now print new formed list
print("Even numbers less than 50 are: ",even_numbers_less_50)

Output:

Even numbers less than 50 are: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48]

Now, by using list comprehension, let's do all that in one line.

# User list comprehension
even_numbers_less_50_v2 = [i for i in range(50) if (i % 2 == 0)]
print("List from comprehension technique", even_numbers_less_50)

Output:

List from comprehension technique [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48]

See, that’s the power of the list comprehension. Simpler list comprehension would be without if and else statements.

Simplest list comprehension = [i for i in range(some_range)]

With if = [i for i in range(some_range) if (some_condition) ]

x_axis=[i for i in range(5)]
print(x_axis)
odd_or_even = ['even' if (num % 2 == 0) else 'odd' for num in range(20)]
print(odd_or_even)

Output:

[0, 1, 2, 3, 4] ['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']

As you can see, as we go on adding conditions, the readability of the code gets worse. Hence, the thumb rule is to use list comprehension unless you want to have a hard time explaining your code after a few days.

Mathematical Operations

We can also perform mathematical operations in the list.

# Mathematics
multiples_5 = [i for i in range(1, 51) if i % 5 == 0]
multiples_4 = [i for i in range(1, 41) if i % 4 == 0]# Print list
print("Multiples of 5:", multiples_5)
print("Multiples of 4:", multiples_4)

Output:

Multiples of 5: [5, 10, 15, 20, 25, 30, 35, 40, 45, 50] Multiples of 4: [4, 8, 12, 16, 20, 24, 28, 32, 36, 40]

Let's do some operations.

# Add a scalar
print(multiples_5+1)

Output:

Traceback (most recent call last):   File "list.py", line 260, in <module>     print(multiples_5+1) TypeError: can only concatenate list (not "int") to list

It gives an error because adding scalar to the list is not possible; you have to loop through each value. Only multiplication operation is supported for scalar.

Some other things you should know about lists that I could not write in this article are nested loops, del() method, list vs NumPy arrays, and concatenation.

This was an extensive guide of Python lists. Throughout this article, I’ve not only introduced list but other benefits of comments, naming conventions, exercises like a palindrome, string multiplications, even and odd numbers, and so on. I hope you got those subtle clues and can use them for your own projects.

--

--

Nibesh Khadka

Software Developer, Content Creator and Wannabe Entrepreneur