- Check the length of a list with the
len()
function - Create a set of unique elements from a list
- Convert a set back to a list
Knowing the length of a list can be useful when you are working with data. In the code console below, we have defined top_travel_cities
. Check the length of this list using the len()
function.
In the code console below, check the length of the list using the len()
function. Pass the name of our list top_travel_cities
as an argument to the function to see how many elements are in our list.
<iframe frameborder="0" width="100%" height="700" src="https://repl.it/@DSExperience/CitiesTry7?lite=true"></iframe>Level up - create your own list and check the length of your list. Add an item or two and see how this affects the output of the
len()
function.
The ability to get a list of the individual or unique elements in a list is very useful. In our list, we have mistakenly added some duplicates. Let's get a set of the unique elements in our list so we can use it to determine which elements have duplicates. Let's assign our new set of unique destinations to a variable, top_cities_set
using the set()
function.
In the code console below, pass the list name top_travel_cities
to the set()
function and assign it to the variable top_cities_set
<iframe frameborder="0" width="100%" height="700" src="https://repl.it/@DSExperience/CitiesTry8?lite=true"></iframe>Level up - try adding more duplicates to the list to see if it affects the outcome of this process. Check the data type of each variable and try to change the set back to a list so it is easier to work with.
In this lesson, you used the len()
function to count the elements in the list. You also used the set()
function to get a set of the unique values in the list and converted the set back to a list to make it easier to use.