List

What is a list?

A list stores an indexed list of items. List values are placed in between square brackets [ ], separated by commas.

ages = [4,12,18]

A list doesn’t contain anything is an empty list.

empty_list = []

range

The range(n) function gives you a list of numbers in order, starting from 0 and going up to and not including n.

For example range(5) would yield [0, 1, 2, 3, 4]

List comprehension

List comprehension is an easy way to create lists in Python.

Example 1

nums = [1, 2, 3, 4, 5]
add_ten = [i + 10 for i in nums]
print(add_ten)
# Output: [11, 12, 13, 14, 15]

Example 2

names = ["Elaine", "George", "Jerry"]
greetings = ["Hello, " + i for i in names]
print(greetings)
# Output: ['Hello, Elaine', 'Hello, George', 'Hello, Jerry']

Example 3

names = ["Elaine", "George", "Jerry", "Cosmo"]
is_Jerry = [name == "Jerry" for name in names]
print(is_Jerry)
# Output: [False, False, True, False]

Example 4

nums = [[4, 8], [16, 15], [23, 42]]
greater_than = [i > j for (i,j) in nums]
print(greater_than)
# Output: [False, True, False]

List operations

  1. The item at a certain index in a list can be reassigned. For example:
nums = [1, 2, 2]
nums[2] = 3
print(nums)
# Output: [1, 2, 3]
  1. Selecting an element that does not exist causes an IndexError.
>>> str = "Hello"
>>> print(str[6])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

Tips: We can get the last element of a list using the -1 index.

  1. Lists can be added and multiplied in the same way as strings.
nums = [1, 2, 3]

print(nums + [4, 5, 6]) 
#Output: [1, 2, 3, 4, 5, 6]

print(nums * 3) 
# Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]
  1. To check if an item is in a list, we use in operator.
nums = [1, 2, 3]
print(2 in nums) #Output: True

3. Slicing list

We can slice list with the following syntax: list[start:end]

  • start is the index of the first element that we want to include in our selection.
  • end is the index of one more than the last index that we want to include. For example
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
sublist = letters[0:3]
print(sublist)
# Output: ['a', 'b', 'c']
  • When starting at the beginning of the list, it is also valid to omit the 0.
sublist = letters[:3]
# Output: ['a', 'b']
  • We can do something similar when selecting the last few items of a list:
sublist = letters[4:]
# Output: ['g', 'h']
  • To select the last element of the list, we can use mylist[-1] syntax.
sublist = letters[-2:] 
# Output the last 2 elements of letters: ['g', 'h']

List functions

len()

To get the number of items in a list, we use the len() function. len() function determine the number of items in the list.

my_list = [1, 2, 3, 4, 5]
print(len(my_list))
# Output: 5

.append()

To add a single element to the end of a list, we use the .append() method.

orders = ["milk", "tea"]
orders.append("sugar")
print(orders) 

# Output: ["milk", "tea", "sugar"]

insert()

To insert a new item at any position in the list, we use insert() function.

words = ["Python", "fun"]
index = 1
words.insert(index, "is")

print(words)
# Output: ['Python', 'is', 'fun']

index()

The index method finds the first occurrence of a list item and returns its index.

nums = [2, 0, 3, 1, 0]
print(nums.index(0))
# Output: 1

.count()

The .count() method counts how many times an element appears in the list.

letters = ['c', 'a', 'i', 'a']
num_a = letters.count('a')
print(num_a)
# Output: 2

.sort()

We can sort a list in place using .sort()

names = ['Hanna', 'Jake', 'Jane', 'April', 'Niles']
names.sort()
print(names)
# Output: ['April', 'Hanna', 'Jake', 'Jane', 'Niles']

Note

  • sort goes after our list. If we try sort(names), we will get a NameError.
  • sort does not return anything. So, if we try to assign names.sort() to a variable, the output would be None:
sorted_names = names.sort()
print(sorted_names)
# Output: None

sorted

sorted is different from .sort():

  • It comes before a list, instead of after.
  • It generates a new list.
  • sorted doesn’t change the list
names = ['Hanna', 'Jake', 'Jane', 'April', 'Niles']

sorted_names = sorted(names)
print(sorted_names)
# Output: ['April', 'Hanna', 'Jake', 'Jane', 'Niles']

print(names)
# Output: ['Hanna', 'Jake', 'Jane', 'April', 'Niles']

zip()

zip() creates a list of lists.

first_names = ['Hanna', 'Ben']
age = [29, 25]
name_and_age = zip(first_names, age)

print(list(name_and_age))
# Output: [('Hanna', 29), ('Ben', 25)]