Custom Search

PYTHON: Storing data

Lists are the simplest way in which multiple data items can be stored within a single variable. It is very useful to have your data stored in a way that makes accessing it easy to do.

There are four built-in data types in Python that can be used to store collections of data.

list() - mutable sequences

tuple() - immutable sequences

set()

dict() - a dictionary

Each one has different qualities and usage.

Lists

Lists are created using square brackets to enclose list items, separated by commas

List items are indexed (so they allow duplicate values), ordered and changeable.

Indexed means each list item is allocated a numbered place in the list - the first item has index [0], the second item has index [1] etc. Since lists are indexed, lists can have items with the same value.

fruit = ["apple", "banana", "cherry", "apple", "cherry", "orange"]

Ordered means that the items have a defined order, and that order will not change. If you add new items to a list, the new items will be placed at the end of the list, not within the existing list items.

Changeable means that you can amend, add, and remove items in a list after it has been created.

The length function

It is useful to be able to count the number of items in a list is useful so Python has a function for doing that.

It is len() - and it returns the length of the list.

numbers = [9, 2, 14, 22, 5, 67, 208, 90, 56]

total= sum(numbers)

print ("Addition sum total = ",total)

print ("Number of items in the list =",len(numbers)