In Python, lists are one of the most commonly used data structures. Lists are a collection of values that are ordered and changeable. This means that you can change, add or remove items in a list after it has been created. Lists can contain different data types such as numbers, strings, or even other lists.
To create a list in Python, you use square brackets []
and separate the values with a comma. Here is an example:
# create a list of numbers
numbers = [1, 2, 3, 4, 5]
You can access elements in a list by their index. The index of a list starts at 0, so the first element in a list has an index of 0. Here is an example:
# create a list of numbers
numbers = [1, 2, 3, 4, 5]
# access the first element in the list
first_number = numbers[0]
print(first_number) # Output: 1
You can add elements to a list using the append()
method. This adds the element to the end of the list. Here is an example:
# create a list of numbers
numbers = [1, 2, 3, 4, 5]
# add a new number to the end of the list
numbers.append(6)
print(numbers) # Output: [1, 2, 3, 4, 5, 6]
You can remove elements from a list using the remove()
method. This removes the first occurrence of the element in the list. Here is an example:
# create a list of numbers
numbers = [1, 2, 3, 4, 5]
# remove the number 3 from the list
numbers.remove(3)
print(numbers) # Output: [1, 2, 4, 5]
Now that you have a basic understanding of lists in Python, let's look at some sample code snippets.
In this easy sample code, we will create a list of fruits and print out the second element in the list.
# create a list of fruits
fruits = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
# print the second fruit in the list
print(fruits[1]) # Output: banana