Lists#

There are four collection data types in Python :

  • List: is a collection which is ordered and changeable(modifiable). Allows duplicate members.

  • Tuple: is a collection which is ordered and unchangeable or unmodifiable(immutable). Allows duplicate members.

  • Set: is a collection which is unordered, un-indexed and unmodifiable, but we can add new items to the set. Duplicate members are not allowed.

  • Dictionary: is a collection which is unordered, changeable(modifiable) and indexed. No duplicate members.

A list is collection of different data types which is ordered and modifiable(mutable). A list can be empty or it may have different data type items.

Create a List#

empty_list = list()  # using built-in function
empty_list
[]
empty_list = []  # using square brackets
empty_list
[]

Lists with initial values. We use len() to find the length of a list.

fruits = ["banana", "orange", "mango", "lemon"]
vegetables = ["Tomato", "Potato", "Cabbage", "Onion", "Carrot"]
animal_products = ["milk", "meat", "butter", "yoghurt"]
web_techs = [
    "HTML",
    "CSS",
    "JS",
    "React",
    "Redux",
    "Node",
    "MongDB",
]
countries = ["Indonesia", "Singapore", "Malaysia", "Thailand", "Vietnam"]

# Print the lists and its length
print("Fruits:", fruits)
print("Number of fruits:", len(fruits))
print("Vegetables:", vegetables)
print("Number of vegetables:", len(vegetables))
print("Animal products:", animal_products)
print("Number of animal products:", len(animal_products))
print("Web technologies:", web_techs)
print("Number of web technologies:", len(web_techs))
print("Countries:", countries)
print("Number of countries:", len(countries))
Fruits: ['banana', 'orange', 'mango', 'lemon']
Number of fruits: 4
Vegetables: ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
Number of vegetables: 5
Animal products: ['milk', 'meat', 'butter', 'yoghurt']
Number of animal products: 4
Web technologies: ['HTML', 'CSS', 'JS', 'React', 'Redux', 'Node', 'MongDB']
Number of web technologies: 7
Countries: ['Indonesia', 'Singapore', 'Malaysia', 'Thailand', 'Vietnam']
Number of countries: 5

Lists can have items of different data types.

list = ["Aurora", 6, True, {"country": "Indonesia", "city": "Palembang"}]
list
['Aurora', 6, True, {'country': 'Indonesia', 'city': 'Palembang'}]

Accessing List Items Using Positive Indexing#

We access each item in a list using their index. A list index starts from 0.

banana

orange

mango

lemon

0

1

2

3

fruits = ["banana", "orange", "mango", "lemon"]
first_fruit = fruits[0]
print(first_fruit)

second_fruit = fruits[1]
print(second_fruit)
last_fruit = fruits[3]
print(last_fruit)

# Last index
last_index = len(fruits) - 1
last_fruit = fruits[last_index]
banana
orange
lemon

Accessing List Items Using Negative Indexing#

Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last item.

banana

orange

mango

lemon

-4

-3

-2

-1

fruits = ["banana", "orange", "mango", "lemon"]

first_fruit = fruits[-4]
last_fruit = fruits[-1]
second_last = fruits[-2]

print(first_fruit)
print(last_fruit)
print(second_last)
banana
lemon
mango

Unpacking List Items#

list = ["item1", "item2", "item3", "item4", "item5"]
first_item, second_item, third_item, *rest = list

print(first_item)
print(second_item)
print(third_item)
print(rest)
item1
item2
item3
['item4', 'item5']
fruits = ["banana", "orange", "mango", "lemon", "lime", "apple"]
first_fruit, second_fruit, third_fruit, *rest = fruits
print(first_fruit)
print(second_fruit)
print(third_fruit)
print(rest)

first, second, third, *rest, tenth = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(first)  # 1
print(second)  # 2
print(third)  # 3
print(rest)  # [4,5,6,7,8,9]
print(tenth)  # 10

countries = [
    "Germany",
    "France",
    "Belgium",
    "Sweden",
    "Denmark",
    "Finland",
    "Norway",
    "Iceland",
    "Estonia",
]
gr, fr, bg, sw, *scandic, es = countries
print(gr)
print(fr)
print(bg)
print(sw)
print(scandic)
print(es)
banana
orange
mango
['lemon', 'lime', 'apple']
1
2
3
[4, 5, 6, 7, 8, 9]
10
Germany
France
Belgium
Sweden
['Denmark', 'Finland', 'Norway', 'Iceland']
Estonia

Slicing Items from a List#

Positive Indexing: We can specify a range of positive indexes by specifying the start, end and step, the return value will be a new list. (default values for start = 0, end = len(lst) - 1 (last item), step = 1)

fruits = ["banana", "orange", "mango", "lemon"]

all_fruits = fruits[0:4]  # it returns all the fruits
print(all_fruits)

# this will also give the same result as the one above
all_fruits = fruits[0:]  # if we don't set where to stop it takes all the rest
print(all_fruits)

orange_and_mango = fruits[1:3]  # it does not include the first index
print(orange_and_mango)

orange_mango_lemon = fruits[1:]
print(orange_mango_lemon)

# below we use a 3rd argument, step. It will take every 2nd item - ['banana', 'mango']
banana_mango = fruits[::2]
print(orange_and_lemon)
['banana', 'orange', 'mango', 'lemon']
['banana', 'orange', 'mango', 'lemon']
['orange', 'mango']
['orange', 'mango', 'lemon']
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[9], line 18
     16 # below we use a 3rd argument, step. It will take every 2nd item - ['banana', 'mango']
     17 banana_mango = fruits[::2]
---> 18 print(orange_and_lemon)

NameError: name 'orange_and_lemon' is not defined

Negative Indexing: We can specify a range of negative indexes by specifying the start, end and step, the return value will be a new list.

fruits = ["banana", "orange", "mango", "lemon"]

# it returns all the fruits
all_fruits = fruits[-4:]
print(all_fruits)

# it does not include the last index,['orange', 'mango']
orange_and_mango = fruits[-3:-1]
print(orange_and_mango)

# this will give starting from -3 to the end,['orange', 'mango', 'lemon']
orange_mango_lemon = fruits[-3:]
print(orange_mango_lemon)

# a negative step will take the list in reverse order,['lemon', 'mango', 'orange', 'banana']
reverse_fruits = fruits[::-1]
print(reverse_fruits)

Modifying Lists#

List is a mutable or modifiable ordered collection of items. Lets modify the fruit list.

fruits = ["banana", "orange", "mango", "lemon"]

fruits[0] = "avocado"
print(fruits)

fruits[1] = "apple"
print(fruits)

last_index = len(fruits) - 1
fruits[last_index] = "lime"
print(fruits)

Checking Items in a List#

Checking an item if it is a member of a list using in operator.

fruits = ["banana", "orange", "mango", "lemon"]

does_exist = "banana" in fruits
print(does_exist)

does_exist = "lime" in fruits
print(does_exist)

Adding Items to a List#

To add item to the end of an existing list we use the method append().

fruits = ["banana", "orange", "mango", "lemon"]
fruits.append("apple")
print(fruits)

fruits.append("lime")
print(fruits)

Inserting Items into a List#

We can use insert() method to insert a single item at a specified index in a list. Note that other items are shifted to the right. The insert() methods takes two arguments: index and the item to be inserted.

fruits = ["banana", "orange", "mango", "lemon"]
fruits.insert(2, "apple")
print(fruits)

fruits.insert(3, "lime")
print(fruits)

Removing Items from a List#

The remove() method removes a specified item from a list.

fruits = ["banana", "orange", "mango", "lemon", "banana"]
fruits.remove("banana")
print(fruits)

fruits.remove("lemon")
print(fruits)

Removing Items Using Pop#

The pop() method removes the specified index, (or the last item if index is not specified).

fruits = ["banana", "orange", "mango", "lemon"]
fruits.pop()
print(fruits)

fruits.pop(0)
print(fruits)

Removing Items Using Del#

The del keyword removes the specified index and it can also be used to delete items within index range. It can also delete the list completely.

fruits = ["banana", "orange", "mango", "lemon", "kiwi", "lime"]
del fruits[0]
print(fruits)

del fruits[1]
print(fruits)

del fruits[1:3]
print(fruits)
del fruits
# print(fruits) # Running this will raise: NameError: name 'fruits' is not defined

Clearing List Items#

The clear() method empties the list.

fruits = ["banana", "orange", "mango", "lemon"]
fruits.clear()
print(fruits)

Copying a List#

It is possible to copy a list by reassigning it to a new variable in the following way: list2 = list1. Now, list2 is a reference of list1, any changes we make in list2 will also modify the original, list1. However, there are lots of case in which we do not like to modify the original instead we like to have a different copy. One of way of avoiding the problem above is using copy().

fruits = ["banana", "orange", "mango", "lemon"]
fruits_copy = fruits.copy()
print(fruits_copy)

Joining Lists#

There are several ways to join, or concatenate, two or more lists in Python.

Plus Operator (+)#

positive_numbers = [1, 2, 3, 4, 5]
zero = [0]
negative_numbers = [-5, -4, -3, -2, -1]
integers = negative_numbers + zero + positive_numbers
print(integers)

fruits = ["banana", "orange", "mango", "lemon"]
vegetables = ["Tomato", "Potato", "Cabbage", "Onion", "Carrot"]
fruits_and_vegetables = fruits + vegetables
print(fruits_and_vegetables)

extend()#

num1 = [0, 1, 2, 3]
num2 = [4, 5, 6]
num1.extend(num2)
print("Numbers:", num1)

negative_numbers = [-5, -4, -3, -2, -1]
positive_numbers = [1, 2, 3, 4, 5]
zero = [0]

negative_numbers.extend(zero)
negative_numbers.extend(positive_numbers)
print("Integers:", negative_numbers)

fruits = ["banana", "orange", "mango", "lemon"]
vegetables = ["Tomato", "Potato", "Cabbage", "Onion", "Carrot"]
fruits.extend(vegetables)
print("Fruits and vegetables:", fruits)

Counting Items in a List#

The count() method returns the number of times an item appears in a list.

fruits = ["banana", "orange", "mango", "lemon"]
print(fruits.count("orange"))

ages = [22, 19, 24, 25, 26, 24, 25, 24]
print(ages.count(24))

Finding Index of an Item#

The index() method returns the index of an item in the list.

fruits = ["banana", "orange", "mango", "lemon"]
print(fruits.index("orange"))

ages = [22, 19, 24, 25, 26, 24, 25, 24]
print(ages.index(24))

Reversing a List#

The reverse() method reverses the order of a list.

fruits = ["banana", "orange", "mango", "lemon"]
fruits.reverse()
print(fruits)

ages = [22, 19, 24, 25, 26, 24, 25, 24]
ages.reverse()
print(ages)

Sorting List Items#

To sort lists we can use sort() method or sorted() built-in functions.

sort()#

The sort() method reorders the list items in ascending order and modifies the original list. If an argument of sort() method reverse is equal to true, it will arrange the list in descending order.

fruits = ["banana", "orange", "mango", "lemon"]
fruits.sort()
print(fruits)  # sorted in alphabetical order, ['banana', 'lemon', 'mango', 'orange']
fruits.sort(reverse=True)
print(fruits)  # ['orange', 'mango', 'lemon', 'banana']
ages = [22, 19, 24, 25, 26, 24, 25, 24]
ages.sort()
print(ages)  #  [19, 22, 24, 24, 24, 25, 25, 26]

ages.sort(reverse=True)
print(ages)  #  [26, 25, 25, 24, 24, 24, 22, 19]

sorted()#

The sorted() function returns the ordered list without modifying the original list,

fruits = ["banana", "orange", "mango", "lemon"]
print(sorted(fruits))  # ['banana', 'lemon', 'mango', 'orange']
print(fruits)

fruits = ["banana", "orange", "mango", "lemon"]
fruits = sorted(fruits, reverse=True)
print(fruits)