Python Tutorial – Lists

python list practice
Reading Time: 10 minutes

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

Intro

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

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

  1. It preservers order of data stored
  2. Easy to manipulate. Comes with many methods as we’ll see earlier.
  3. Mutable –> can be changed.

Creating a List

List can be created using by 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 instance, 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 a position in a list but it is not as we would count. In python index starts from zero(0) not one(1). This is the same for other data types like strings and is also similar logic for other programming languages.

Let’s not get confused, and go to coding. In python, we can find an index of an item in a list with index(), function.

# Indexing 
vowel_letters=['a','e','i','o','u']

#Print the list
print(vowel_letters)

#Print the length of list
print("Length of vowel_letters is {}".format(len(vowel_letters)))

#Print the position of items
print("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 a last of 4. Hence, whenever you want to find an 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. List item can be accessed as: For one item: list_name[index].

# Accessing Items in list
odd_numbers =[1,3,5,7,9]
even_numbers=[2,4,6,8,10]

#Print list 
print("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 list, accessing multiple items is done by slicing. 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 comprehension
odd_number_less_100 = [i for i in range(0, 100) if (i % 2 != 0)]

#Print the odd Numbers
print(odd_number_less_100)

#Print new line to create gap 
print("\n")

# Slicing the items
print("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 stop
print("Items from index 10th and 30th index in the list: ",odd_number_less_100[10:30])

# Slice using start and step
print("Items starting from 5th index with +10 jump: ",odd_number_less_100[5::10])

print("\n")

#slice using stop and steps
print("Items with the jump of 5 until the index of 40 ",odd_number_less_100[:40:5])


# Slice with only jumps or steps
print("\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]

I hope there was every variations of examples possible.

Methods In List

Copy()

Copy is a very important method in list object. As the name suggest 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 copy 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 copy
clrs_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 method to add items in the list. The special thing about insert is you can choose 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 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 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 the index of item in your list before which you want to insert new item.
  2. Item is the new value you want to add.
# List of even numbers from 10 to 20
even_number_frm_10_20= [i for i in range(10,21) if i%2==0]

#Print the list
print("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 insertion
print("\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 item 
extended_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

Append method aids to add item to the end of the list. It is similar to using 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 list
animals_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

Insert can help to add item anywhere. Only drawback is you have to know the index, so coding can get complicated depending on situation.

Append can only add item in the end of list. Its very simple and easy but you have to control over the index of item to be added.

Remove

Just like adding items there are methods to remove them. Remove helps the remove an 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 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 form the list. However, it only deletes first matching item, also you have to know the content of the list beforehand.

Pop offers less options, only removes last item. However, you do not necessarily have to know the context.

Count

If you want to find out 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 builtin sorted method in python. It can help sort list in ascending or descending order. It modifies the list but does not return anything.

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

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

The value of each parameter is 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]
None
After random list:, [2, 6, 10, 24, 82, 92, 500]

You are not mistaken, you did saw None in second output line. Its 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. Its a programming character. A None is a data type in python meaning nothing.

Lets 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 comprehensions 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 values we got from 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 item itself but the logic in key attribute. If not sure compare to the dictionary values and see which one should be sorted first.

And don’t worry about lambda. Its a way to write anonymous function for one time use.

Reverse

It reverses the items in the list. Its not as sort(reverse=True) because sort order items by some form of comparison however, reverse just re-orders 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: madam
List 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 same spelled backwards. 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 palindrome verify problem.

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

For and List

For is a looping technique in python. I will write separate article on loops. For is used to create, loop over and modify 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 intials, lets 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 list and for loops.

List Comprehensions

If you’ve read the article from the beginning you’ve already noticed me creating list using list comprehensions. It basically, one lines the for loop part for list creation we saw in 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 lets 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 and elses = [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 code gets worse. Hence, thumb rule for using list comprehension if you have hard time explaining your code after few days.

Mathematical Operations

We can also perform mathematical operations is 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]

Lets 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 error because adding scalar to list is not possible you have to loop through each value. Only multiplication operation is supported for scalar.

Other things you should know about list that I could not write in this article are nested loops, del() method, list vs numpy arrays, concatenation of lists .

This was an extensive guide of python list. Through out this article I’ve not only introduced list but other benefits of comments, naming conventions, exercises like palindrome, string multiplications, even and odd numbers and so on . I hope you got those subtle clues and can use them for your creation. You can find extra exercises from the zip download below, download and practice if you are interested.

Leave a Reply

%d bloggers like this: