Skip to content

Latest commit

 

History

History
49 lines (27 loc) · 2.09 KB

p_16_useful_list_tools_lab.md

File metadata and controls

49 lines (27 loc) · 2.09 KB

Useful List Tools - Lab

More List tools - Lab


Objectives for this lesson


  • 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

Checking the length of a list with the len() function


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.

Try it out


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.

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.

<iframe frameborder="0" width="100%" height="700" src="https://repl.it/@DSExperience/CitiesTry7?lite=true"></iframe>

Create a set of unique elements from a list


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.

Try it out


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

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.

<iframe frameborder="0" width="100%" height="700" src="https://repl.it/@DSExperience/CitiesTry8?lite=true"></iframe>

Recap


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.