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.

Run the program to see the output

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.

Run the program to see the output

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

Run the program to see the output

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.

Run the program to see the output

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.

Run the program to see the output

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.

Run the program to see the output

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.

Run the program to see the output

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.

Run the program to see the output

Loading Exercise...