Python Programming Primer

Data Collections and Looping


Data collections

Python has a handful of data collections, including lists, tuples, sets, and dictionaries. The following outlines how to declare and assign values to these data collections.

The contents of lists, sets, and dictionaries can be changed after they have been created. The contents of tuples on the other hand cannot be changed; they are essentially immutable lists.

Setting and accessing values

Setting and accessing values in lists and dictionaries is done using the square brackets. The following outlines how to set and access values of a list.

The following outlines how to set and access values of a dictionary.

Adding and removing values

Adding values to a list and removing values from the list is done with collection-specific methods. For instance, the following outlines how to add and remove items from a list.

For dictionaries, there is no specific method. Instead, the del keyword is used to remove a key-value pair. The following outlines how to add and remove values from a dictionary.

Python has also basic collection operators, including in and not in. These can be used to check whether a value is in a collection or not. The collection operators return a boolean value. The following outlines the use of the collection operators.


Loading Exercise...

Loops

Python features for and while types of loops. The for loop is used to iterate over values in a collection, whereas the while loop is used to iterate until a condition is met.

The following demonstrates the for loop for iterating over the values of a list.

The following does the same, but with a while loop. When using the while loop, a counter is used to keep track of the current index. The function len that is used below in conjunction with the counter returns the size of the collection given to it.


Loading Exercise...