Python Lists (Part 1)

ยท

3 min read

Lists are one of the common concepts to work with in a python program. In this chapter, we will be going through what lists are and some of the common methods available

What are Lists?

Just as the name implies, a LIST is a collection of items. Lists are also one of the common things you'll come across in a python program. For example, you may want to store the number of users registered on your website in a list and perform some operations on the list as more users are added or removed.

A typical example of a collection of items is a list of groceries to buy. But, in this case, lists are represented with [] and can have as many items as you want. Here's an example;

groceries = ['milk', 'sugar', 'cereal', 'cutlery', 'noodles']

You can access each item in a list by calling the index position of that item

groceries[0] = 'milk'
groceries[1] = 'sugar'
groceries[2] = 'cereal'

NOTE: Index positions in a list start at 0 and not 1. So the position for the first item is 0

Each item in a list is separated with a comma and strings are placed in single quotes ''.

There are a number of operations you can perform on a string and I'll list them below

  • Add an item
  • Remove an item
  • Modify a list
  • Sort a list

We will cover the first operation in this part of the series.

Adding an Item to a List

You can add an item to a list in 2 ways;

The append() method: Using this method on your list adds the item to the end of your list.

Let's add another item to our groceries list, then we will have

groceries.append('chocolate')

Our new list will now be;

['milk', 'sugar', 'cereal', 'cutlery', 'noodles', 'chocolate']

Voila! It's that simple

The insert() method: The insert method adds an item to the position specified. Remember that items in a list are represented with index positions.

An example of using the insert method is

groceries.insert(2, 'soap')

This will make the new list look like this;

['milk', 'sugar', 'soap', 'cereal', 'cutlery', 'noodles', 'chocolate']

Notice what happened there? Our code inserted the new item in the position we specified, which is 2.

This means soap will be the third item in our list (because index positions start from 0 of course) and pushes every other item after it behind.

This reminds me of how queues work and someone cutting in ๐Ÿ˜  ๐Ÿ˜‚

So far we have been able to cover the basics of what a list is and the operations that can be performed on it. We will cover the remaining operations in the following parts of the series.

ย