Introduction to Lists in Python
Lists are ordered collections of items that can store elements of different data types. In this lesson, you will learn how to create lists, how to access elements within a list, and how to get some information about the contents of a list.
So far, we have only worked with individual values like strings and integers, each stored in a separate variable, like this:
str = 'Hello World'
num = 10
Let's say you want to store a collection of names. Instead of creating a separate variable for each name, you can create one variable called names that contains a series of names:
names = ['John', 'Mike', 'Sara', 'Emma']
In Python, this is called a list.
You can put values of any type inside a list. It can even contain values of different types. All of the following are valid lists:
strings = ['a', 'b', 'c']
numbers = [1, 2, 3]
mixed = ['a', 2, True]
You can also nest lists within other lists:
lists = [[1, 2, 3], ['a', 'b', 'c']]
You can access elements in a list using their index, exactly like we did with the characters of a string:
nums = [1, 2, 3]
# get first element
print(nums[0])
# get second element
print(nums[1])
# get last element
print(nums[-1])
Just like with strings, the first element of a list has index 0, the second index 1, and so on...
If you want to get a range of elements from a list, use slicing:
nums = [1, 2, 3, 4, 5]
# range from second to third element
print(nums[1:3])
# exclude first element
print(nums[1:])
# exclude last element
print(nums[:-1])
# copy of the entire list
print(nums[:])
If you want to know how many elements a list has, you can use the len()
function:
nums = [1, 2, 3]
# get length of list
print(len(nums))
Last but not least, you can check if a specific element exists in the list using the in
operator.
value in list
For example, here we check if the strings 'banana' and 'orange' are in the list. If found, the value in list
syntax evaluates to True
; otherwise, it returns False
:
fruits = ['apple', 'banana', 'cherry']
# is 'banana' in fruits?
print('banana' in fruits)
# is 'orange' in fruits?
print('orange' in fruits)
What will be the output?
numbers = [1, 2, 3, 4, 5]
print(numbers[1])
What will be the output?
num = 10
numbers = [1, num]
print(numbers[1])
What will be the output?
numbers = [1, 2, 3, 4, 5]
print(numbers[1:])
What will be the output?
numbers = [1, 2, 3, 4, 5]
print(numbers[1:-2])
What will be the output?
numbers = [1, 2, 3, 4, 5]
print(2 in numbers)
What will be the output?
numbers = [1, 2, 3, 4, 5]
print('2' in numbers)
What will be the output?
numbers = [1, 2, 3, 4, 5]
print(len(numbers))
What will be the output?
numbers = [[1,2,3], [4,5,6]]
print(len(numbers))