A list stores an indexed list of items. List values are placed between square brackets [ ], separated by commas.
ages = [4,12,18]
A list that doesn’t contain anything is an empty list.
empty_list = []
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 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]
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]
Selecting a non-exist element 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.
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]
To check if an item is in a list, we use the in
operator.
nums = [1, 2, 3]
print(2 in nums) #Output: True
We can slice the list with the following syntax: list[start:end]
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
sublist = letters[0:3]
print(sublist)
# Output: ['a', 'b', 'c']
sublist = letters[:3]
# Output: ['a', 'b']
sublist = letters[4:]
# Output: ['g', 'h']
mylist[-1]
syntax.sublist = letters[-2:]
# Output the last two elements of letters: ['g', 'h']
To get the number of items in a list, we use the len()
function.
The len() function determines the number of items in the list.
my_list = [1, 2, 3, 4, 5]
print(len(my_list))
# Output: 5