Lists are a collection of data and are represented with square brackets [ ] . With lists, data is stored in sequence.
Lists are mutable, meaning that we can modify and change the content of lists using many methods. Lists can contain different types of data.
listOfFruits = ["apples", "bananas", "cherries"]
In this example, listOfFruits is the variable that we have assigned our list to.
Each element in the list has a specific index. We can access elements in a list via their index.
The first item in the list has an index of 0 , second item has index of 1 and so on.
Negative Indexing is when you refer to the items from the end. -1 refers to the last item, -2 refers to the second last item and so on.
Negative indexing Example
To access a range of items in a list, we use the slice operator :
list[start index:stop index] list[0:3]
The stop index item will not be included in the range.
We can add elements to a list using the append , extend and insert methods. Below is how you can apply the methods to your lists.
We can add a single element to the end of the list using the append method.
"blueberries" is a string element that we would like to add to the end of myList.
Can we add multiple elements using the append method?
No, append only takes a single item as a parameter. Thus, in this case, blueberries and cantaloupes will be considered as 1 element when appended.
We can insert multiple elements to a list using the extend method.
We can insert a single element at a specified position in a list using the insert method.
2 represents the index of the element before the new element that you want to insert.
"blueberries" represent the element that you are inserting into the list.
We can remove elements from a list using the remove , pop and delete methods. Below is how you can apply the methods to your lists.
We can remove a single element as an argument.
We can remove an element by referring to its index number. pop() returns the removed element.
We can delete an element by referring to its index number.
1. Create and print a list with these elements: Adam, Adora, Ella
2. List indexing: Find the third element in the list
3. List slicing: Access the last 2 items in the list
4. Add these elements to the list using the append and extend methods: Lila, James
5. Insert this element to the list after the second element: Lila
6. Remove Adam from the list
7. Remove the second element from the list using pop and delete