Python List

1. INTRODUCTION TO PYTHON’S LIST

1.1. What Is a List?

  • A list is a collection of items in a particular order.

  • In Python, square brackets [] indicate a list, and individual elements in the list are separated by commas.

  • List can contain heterogeneous data, means, your list can contain integer, strings, floats

  • Naming Tip: Because a list usually contains more than one element, it’s a good idea to make the name of your list plural, such as letters, digits, or names. Here is an example of list

wrestlers = ['John Cena','Rock','Rick Flair','Goldberg']
print(wrestlers)
['John Cena', 'Rock', 'Rick Flair', 'Goldberg']

1.2. Indexing (Accessing Elements in a List)

To access an element in a list, provide the name of the list followed by the index of the item enclosed in square brackets. For example, we want to access the first element in the list wrestlers Index starts from zero (0), therefore to access the first item in the list, provide wrestlers[0]

wrestlers = ['John Cena','Rock','Rick Flair','Goldberg']
print(wrestlers[0])
John Cena

We can also apply any method while printing the element. For example, as we have covered in part 1, let’s convert the string to upper case using upper() method

wrestlers = ['John Cena','Rock','Rick Flair','Goldberg']
print(wrestlers[0].upper())
JOHN CENA

1.3. Position of Elements in the List

For a list of n elements, the index level starts from 0 and ends at n-1 In addition, Python has a special syntax for accessing the last element in a list. — by providing index value of -1. In this way, the index -2 returns the second last item , the index -3 returns the third last item, and so forth.

Let’s fetch the last item from the list wrestlers by using wrestlers[-1]

wrestlers = ['John Cena','Rock','Rick Flair','Goldberg']
print(wrestlers[-1])
Goldberg

Therefore, the index values from left to right would be:

[0,1,2,3,4,5 ...]

And Index values from right to left would be:

[... -3,-2,-1]

1.4. Using Individual Values from a List

Let’s apply our knowledge up-to this point by pulling (my favorite) wrestler from the wrestlers list and compose a message using that value:

wrestlers = ['John Cena','Rock','Rick Flair','Goldberg']
message = f"My favorite wrestler is {wrestlers[1]}"
print(message)
My favorite wrestler is Rock

2. CHANGING, ADDING, AND REMOVING ELEMENTS

In this section, our focus is to learn technique to modify the elements of the list. Suppose we are storing favorite cars in the list cars Let’s print the list and also its data type:

cars = ['Honda','Toyota','BMW','Cadillac','Tesla']
print(cars)
print(type(cars))
['Honda', 'Toyota', 'BMW', 'Cadillac', 'Tesla']
<class 'list'>

Now lets modify the element of this list, here are the possible cases:

2.1. Modifying Elements in a List

I would like to modify the element BMW with Mercedes in my list. To do this, we will use the index position of the element BMW and then declare new value Mercedes at that position:

cars = ['Honda','Toyota','BMW','Cadillac','Tesla']
print(f"Before Modification: {cars}")
cars[2] = 'Mercedes'
print(f"After Modification: {cars}")
Before Modification: ['Honda', 'Toyota', 'BMW', 'Cadillac', 'Tesla']
After Modification: ['Honda', 'Toyota', 'Mercedes', 'Cadillac', 'Tesla']

2.2. Adding Elements to a List

Now, we would like to add a new car to list of cars

a. Appending Elements to the End of a List

When you append an item to a list using .append() method, the new element is added to the end of the list.

cars = ['Honda', 'Toyota', 'Mercedes', 'Cadillac', 'Tesla']
cars.append('Ford')
print(cars)
['Honda', 'Toyota', 'Mercedes', 'Cadillac', 'Tesla', 'Ford']

b. Inserting Elements into a List

You can add a new element at any position in your list by using the insert() method.** ** We can do this by specifying the index position of the new element and the value of the new item, inside the ( )

cars = ['Honda', 'Toyota', 'Mercedes', 'Cadillac', 'Tesla']
cars.insert(0,'Ford')
print(cars)
['Ford', 'Honda', 'Toyota', 'Mercedes', 'Cadillac', 'Tesla']

2.3. Removing Elements from a List

We can remove element from the list based on its position or value

a. Removing an Item Using the del Statement

If you know the position of the item you want to remove from a list, you can use the del statement. Note, that del is a statement and not a method

cars = ['Honda', 'Toyota', 'Mercedes', 'Cadillac', 'Tesla']
del cars[-1]
print(cars)
['Honda', 'Toyota', 'Mercedes', 'Cadillac']

💡Remember: You can no longer access the value that was removed from the list after the del statement is used.

b. Removing an Item Using the pop() Method

Sometimes you want to use the value of an item after you remove it from a list. In such cases, we should use pop() method. To pop the last item, we can use pop() with empty () Here is a quick demonstration of this concept:

cars = ['Honda', 'Toyota', 'Mercedes', 'Cadillac', 'Tesla']
print(cars)
popped_car = cars.pop()
print(cars)
print(popped_car)
['Honda', 'Toyota', 'Mercedes', 'Cadillac', 'Tesla']
['Honda', 'Toyota', 'Mercedes', 'Cadillac']
Tesla

c. Popping Items from any Position in a List

We can actually use pop() to remove an item in a list at any position by including the index position of the item we want to remove in parentheses () Let suppose, we would like to pop the first element in the list:

cars = ['Honda', 'Toyota', 'Mercedes', 'Cadillac', 'Tesla']
first_car = cars.pop(0)
print(f"First car in the list is {first_car}.") 
First car in the list is Honda.

💡 del or pop() ?

  • If you want to delete an item from a list and do not want to use that item later, use the del statement,

  • if you want to use an item after you remove it from the list, use the pop() method

2.4. Removing an Item by Value

If you only know the value of the item you want to remove, you can use the remove() method.

cars = ['Honda', 'Toyota', 'Mercedes', 'Cadillac', 'Tesla']
print(cars)
cars.remove('Tesla')
print(cars)
['Honda', 'Toyota', 'Mercedes', 'Cadillac', 'Tesla']
['Honda', 'Toyota', 'Mercedes', 'Cadillac']

If you want to work with the value being removed, then you can first store it inside a variable

cars = ['Honda', 'Toyota', 'Mercedes', 'Cadillac', 'Tesla']
print(cars)
electric_car = 'Tesla'
cars.remove(electric_car)
print(cars)
print(f"Electric cars are not available in the country so I removed {electric_car} from your list") 
['Honda', 'Toyota', 'Mercedes', 'Cadillac', 'Tesla']
['Honda', 'Toyota', 'Mercedes', 'Cadillac']
Electric cars are not available in the country so I removed Tesla from your list

💡 Remember: The remove() method deletes only the first occurrence of the value you specify. If there’s a possibility that the value appears more than once in the list, you’ll need to use a for loop to determine if all occurrences of the value have been removed. We will study for loops later in part 3.

3. ORGANIZING A LIST

In this section we will study few methods to organize the content of the list.

3.1. Sorting a List Permanently with the sort() Method

Python’s sort() method makes it relatively easy to sort a list. In this example, ee will work with the list of cars and change the order of the elements in the list, to store them alphabetically.

cars = ['honda', 'toyota', 'mercedes', 'cadillac', 'tesla']
print(f"Before sort: {cars}")
cars.sort()
print(f"After sort: {cars}")
Before sort: ['honda', 'toyota', 'mercedes', 'cadillac', 'tesla']
After sort: ['cadillac', 'honda', 'mercedes', 'tesla', 'toyota']

We can also sort this list in reverse alphabetical order by passing the argument reverse=True to the sort() method.

cars = ['honda', 'toyota', 'mercedes', 'cadillac', 'tesla']
print(f"Before sort: {cars}")
cars.sort(reverse=True)
print(f"After reverse sort: {cars}")
Before sort: ['honda', 'toyota', 'mercedes', 'cadillac', 'tesla']
After reverse sort: ['toyota', 'tesla', 'mercedes', 'honda', 'cadillac']

💡Remember : The sort() method changes the order of the list permanently.

3.2. Sorting a List Temporarily with the sorted() Function

The sorted() function lets you display your list in a particular order but doesn’t affect the actual order of the list

cars = ['honda', 'toyota', 'mercedes', 'cadillac', 'tesla']
print(f"Original list:\n {cars}")
print(f"\nAfter sorted function is applied to the list:\n {sorted(cars)}")
print(f"\nHere is the original list again:\n {cars}")
Original list:
 ['honda', 'toyota', 'mercedes', 'cadillac', 'tesla']

After sorted function is applied to the list:
 ['cadillac', 'honda', 'mercedes', 'tesla', 'toyota']

Here is the original list again:
 ['honda', 'toyota', 'mercedes', 'cadillac', 'tesla']

The sorted() function can also accept reverse=True keyword argument, if you want to display a list in reverse alphabetical order.

3.3. Printing a List in Reverse Order

To reverse the original order of a list, you can use the reverse() method

cars = ['honda', 'toyota', 'mercedes', 'cadillac', 'tesla']
print(f"Before reverse: {cars}")
cars.reverse()
print(f"After reverse: {cars}")
Before reverse: ['honda', 'toyota', 'mercedes', 'cadillac', 'tesla']
After reverse: ['tesla', 'cadillac', 'mercedes', 'toyota', 'honda']

💡reverse() method doesn’t reverse based on alphabetic order, it just reverse the order of items in the original list. * The reverse() method changes the order of a list permanently*, but you can revert to the original order by applying reverse() to the same list a second time.

3.4. Finding the Length of a List

You can find the length of a list (that it, number of elements in the list) by using the len() function.

cars = ['honda', 'toyota', 'mercedes', 'cadillac', 'tesla']
print(f"There are total {len(cars)} elements in the list")
There are total 5 elements in the list

3.5. IndexError

An IndexError means Python can’t figure out the index we have asked for. Let’s say you have a list with five items, and you ask for the sixth item:

cars = ['honda', 'toyota', 'mercedes', 'cadillac', 'tesla']
print(cars[5])
IndexError: list index out of range

💡If an IndexError occurs and you can’t figure out how to resolve it, try printing your list or just printing the length of your list.

Last updated