Editing lists in Python

Coding with Python

🕑 This lesson will take about 30 minutes

Merging lists

We already know that we can join strings together which we looked at in the lesson on strings. In the same way that strings can be joined (concatenated), we can also join lists. Remember that lists and strings are both types of sequences, so if you are joining strings together or joining lists together, you are essentially joining sequences together.

To join two lists together, it’s the same as if you were joining strings together: you use the + sign. In the example below, we have two lists that each contain numbers. The first list is called list_a and the second list is called list_b. To add them together, we just write list_a + list_b and Python joins them together. We can store the result in a new list, for example a list called merged_list. Here is some sample code for this example.

Membership

In Python, there is something called the in operation. The in operation basically looks at a sequence (such as a string or a list) and checks whether a specified value exists in that sequence. If an element exists in the sequence, then it is said that it is a member (or has membership) of that sequence.

Lets look at how to use the in operation to check for members of a sequence. Firstly, lets use a simple string as an example. We’ll make a variable called mystring with the string value of "potato". We can check if certain characters are in this string such as the letter ‘zʼ or the letter ‘pʼ. To test this, we could write, for example, 'z' in my_string which will either return True or False. We could put this inside a print() function call to display the result of this test on screen, for example print('z' in my_string). The letter ‘zʼ is not in the word ‘potato’, so the it will return False. Howver, the letter ‘pʼ is definitely in the word ‘potato’, so if we wrote print('p' in my_string) then it will return True. Check out the example below.

Python returns False when we check 'z' in the string variable because it knows there is no letter 'z' in the word potato. Python returns True when we check 'p' in the string because it knows there is definitely a letter 'p' in the word potato. So now that we know how to use the in operation on a string, let’s try it on a list sequence to check if an element belongs to a list. Check out the examples below.

The in operation will come in handy later on when we start working with if/else statements which are used to make decisions in our programs based on different conditions, and when we start handling user input more, so itʼs handy to know!

There is also a not in operation that can be used if you want to check if something doesn’t exist in a sequence as shown in the examples below.

Checking the length of sequences

Another function you can use with sequences is the len() function which will tell you the length of a sequence such as the length of a string, list, or tuple. If you use the len() function on a string it will tell you the number of characters in that string (eg. can be useful for checking the length of a string such as a username, password, word or sentence). If you use the len() function on a list, it will tell you the number of elements in that list. See below:

Finding the smallest and largest values in a list

The min() and max() functions can be used to tell you the minimum and maximum values in a list (the lowest and highest numbers, for example). Lets say we have a list full of random numbers and we want to know what the smallest and largest numbers are in that list. We have a list called numbers and it has been given some random numbers. To get the minimum value, we would write min(numbers). To get the maximum value, we would write max(numbers). In our list of numbers below, Python tells us that 2 is the lowest number (min) and 89 is the highest number (max).

Convert a string to a list

The list() function can also take a string and convert it into a list. Say we want to break up the letters in the word “basketball” and make each letter an element in a list called letters. We can make a list called letters and then the list() function to convert the string into a list. Then, if we use the print statement to print out the list, it will print out each separate element in the list (each individual letter). We can also get the value from an individual element in the list using its index, eg element at index position [4] which is the letter ‘eʼ in the example below.

One scenario where you might want to convert a string to a list in Python is where the string represents a sequence of items, and you want to break it down into individual elements for further processing. For example, suppose you have a comma-separated string representing a list of names (this could have been imported in this format from a text file, or received from user input. for example) and you want to convert it into an actual list of names. The split() method can come in handy here.

The split() method is used to split the smaller segments (substrings) of a string into a list of elements based on a character (or sequence of characters) that separates the substrings. For example, if you have a string containing names each separated by a comma, then the comms (,) is the character that separates each substring (each name) in the string, and can be used by the split() function to take these names and make them elements in a list. Check out the example below.

You can also customise the split() method to handle different delimiters or whitespace. For example, if the names were separated by spaces, you could use split() without passing any arguments, or if there was a space after each comma separating the names, you could write split(", ") .

Changing elements in a list

When we have made a sequence such as a list or string (but not tuples), we can change an element in that sequence if we wish later on. All we have to do is tell Python which element from a sequence we want to change and what we want to change it to. Firstly, we reference the element from the sequence (remember that we reference an element by its index. Index numbering begins from 0 in a sequence). So, if we want to change the number 50 in the list below and replace it with the number 45, we would reference the element first by its index which is [4] and change it to the new number we want by typing numbers[4]=45.

Deleting elements from a list

So now we know that we can change an element in a list but we can also delete an element from a list too. To delete an element from a list, we use the del keyword and tell Python which element we want to delete from the chosen list. Say that we want to delete the number 30 from our list called numbers. We would tell Python to delete numbers[2] as the number 30 is indexed as [2] in the numbers list. We would write del numbers[2] .

Here are a couple of examples.

Replacing elements in a list

We looked at different examples of slicing in the previous lesson. In this lesson, we will look at how to use slicing to replace or insert new elements into an existing list. In the example code below, we have a list containing different foods. We can use slicing to replace some of the existing elements (foods) in the list with new elements (foods). In the example, we replace “pie” and “cake” with “wings” and “nuggets”.

In the example below, two elements are replaced with three new elements (eg. “pie” and “cake” are replaced with “wings”, “nuggets”, and “dumplings”. The existing two elements are removed and three new elements are inserted in their place.

Inserting elements in a list

We can also use slicing to insert elements into a list. In the example below, we will insert new foods into the existing list (without replacing any existing foods). If we tell Python to start at index [1] and end at index [1] it will add the new elements before the existing element in index position 1. Tip: We can do the same to strings (eg. insert extra characters in a string by converting the string to a list using the list() function first, and then using the same slicing technique shown here).

Another way of deleting elements from a list (instead of using the del function) is to replace elements you want to delete with nothing (an empty element). For example, if you typed in names[2:5]=[] it would remove elements 2, 3, and 4 from the list (keep in mind this will remove the elements from the list, not just replace them with empty elements, essentially reducing the length of the list). Check out the example code:

Next lesson: List methods