We have just learned about creating and using lists. Let's move on to some of the more advanced things you can now do with them.
Ensure that you are signed into GitHub
Open the assignment: Project 5 - To Do List
Open lab2.py
Iterating through a list means going through each element one by one. This is typically done using a for loop in Python.
The for loop sets up a temporary task variable for each iteration. This holds the value of the current element as it loops through the list, one by one.
Elements can be removed from lists using methods like remove() (removes a specific item) and pop() (removes an item at a given position).
Sorting rearranges the elements of the list in a specified order (default is ascending). The sort() method sorts the list in place.
To check if an item exists in a list, the in keyword is used. It returns True if the item is found, and False otherwise.
You can also find the first occurrence of an item using the index() method.
Notice that "cherry" is in the list twice, but it only returns the first index that it is found.
Slicing is used to create a new list out of a segment of an existing list. It is done by specifying the start and end indices of the slice.
Complete the exercises found in Lab 2 which cover:
Removing items from a list
Searching the list
Sorting the list
Slicing the list
Press Ctrl + F5 to run the program or open a terminal and type python lab2.py
You should now know how to use some of the more advanced features of lists in Python.
Let's wrap up this lab by pushing our code to GitHub:
Enter a commit message. E.g. "Lab 2 complete"
Press Commit to main
Press Push origin