EAFP - Literals - Lists, Tuples, Sets, Dictionaries

Lists, Tuples, Sets, Dictionaries

Python has syntactic support for the creation of container types.

Lists (class list) are mutable sequences of items of arbitrary types, and can be created either with the special syntax

a_list =

or using normal object creation

a_second_list = list a_second_list.append(4) a_second_list.append(5)

Tuples (class tuple) are immutable sequences of items of arbitrary types. There is also a special syntax to create tuples

a_tuple = 1, 2, 3, "four"

Although tuples are created by separating items with commas, the whole construct is usually wrapped in parentheses to increase readability. An empty tuple is denoted by .

Sets (class set) are mutable containers of items of arbitrary types. The items are not ordered, but sets support iteration over the items. A syntax for set creation appeared in Python 2.7/3.0

some_set = {0, False}

In earlier Python versions, sets would be created by calling initializing the set class with a list argument. Python sets are very much like mathematical sets, and support operations like set intersection and union.

Python also features a frozenset class for immutable sets.

Dictionaries (class dict) are mutable mappings tying keys and corresponding values. Python has special syntax to create dictionaries ({key: value})

a_dictionary = {"key 1":"value 1", 2:3, 4:}

The dictionary syntax is similar to the set syntax, the difference is the presence of colons. The empty literal {} results in an empty dictionary rather than an empty set, which is instead created using the non-literal constructor: set.

Read more about this topic:  EAFP, Literals

Famous quotes containing the word dictionaries:

    We never say so much as when we do not quite know what we want to say. We need few words when we have something to say, but all the words in all the dictionaries will not suffice when we have nothing to say and want desperately to say it.
    Eric Hoffer (1902–1983)