Python challenge: Handling lists
Here are some very simple operations that can be performed on lists:
Initialize an empty list
Adding a string to the list
Inserting a new string at a custom position
Deleting an item from the list
One way of deleting an item is the del
function:
Another alernative is the remove
function:
Note that this call can cause a ValueError
, if the list does not contain such an object.
Checking if the list contains a certain string
The function count
returns a value larger than 0, if the list contains the string in question.
Sorting the list
Getting the size of the list
Lists that contain complex objects
Of course, lists can also contain non-primitive objects. The following code iterates through a list of objects of type Contact
and calls the displayContact
function.
Sorting the list based on a certain criteria
Lists that contain complex atttributes can be sorted based on such an attribute.
This will sort the contact list ascending based on their firstname. The sorted
function returns a new, sorted list and keep the original list unchanged. The content of the new list is as follows:
Using list comprehension
Above, I have used a standard for loop to iterate through a list. This can be replaced by a list comprehension:
A comprehension contains an expression followed by a for
statement. The idea of comprehensions is to shorten the code and to make it easier to read.
Filtering a list using list comprehension
Comprehensions can be also used to filter lists, that is we can search through a list for matching items. The following example finds all contacts that have phone numbers containing the number 1:
Further resources
A working example can be found on github