List

I. 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 = []

II. 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]

III. 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]

IV. List operations

1. Reassign item

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]

2. Select item

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.

3. Math operators

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]

4. Check item in a list

To check if an item is in a list, we use in operator.

nums = [1, 2, 3]
print(2 in nums) #Output: True

5. 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']

6. 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