Skip to content

Collections

What are collections?

Collections are containers (variables of a complex type) that can aggregate more than one value.

  • list (list) - a collection containing many values ​​of different types, which can be freely enlarged and shortened; each element of the list has its own index through which it can be accessed,
  • dictionary (dict) - just like the list, with the elements not necessarily indexed by numbers from 0 to the length of the collection - 1, only keys that can be, in addition, strings, Boolean values, and even the value None,
  • short (tuple) - a list which cannot be changed once defined; each item is under a specific index.
  • set (set) - a collection of unique values ​​of different types; non-indexable, elements cannot be accessed.

List

The following are the characteristics of variables of the type list with examples of how to handle values ​​of this type.

  • The list is defined by entering between [ signs and ] elements that should be included in it.
  • Lists are ordered - each element has its own index, order is important!
  • The list can store many values ​​of various types.
  • The value from the list is accessed via the index at which it is located.
  • Lists can contain different types, and thus lists that contain other lists, etc. Lists can be nested any number of times (of course, within reason, reading and accessing elements of such a list will be extremely tedious).
  • Lists are modifiable, elements can be exchanged, deleted, added and we will still be dealing with the same object.
  • Lists are dynamic, they can be expanded on a regular basis, you do not need to know before starting the program, to what maximum sizes the list can grow.

List declaration

    # Declare and initialize letter variable
    alphabet = [] # Declares an empty list
    print(f "Current length of the alphabet variable: {len(alphabet)}") # Prints the number of elements in the list

Appending items to the end of the list

The append() function is used to append items to the end of the list. It is always called on a list variable, which is why you need the hull operator here, i.e. the dot.

    # Let's add some letters to the variable from the previous slide
    alphabet.append( "a")
    alphabet.append( "b")
    alphabet.append( "c")
    print(f "Alphabet: {alphabet} (length: {len(alphabet)})") # Prints the content and length of the list

Indexing lists

As with strings, items in the list are indexed (counted) from 0!

    # Indexing
    alphabet = ['a', 'b', 'c', '...', 'z']
    print(f "The first letter of the alphabet is '{alphabet [0]}'.")
    print(f "And the last letter of the alphabet is '{alphabet [-1]}'.")

Extending the list with items from another list

The extend() function allows you to add multiple items to the list at the same time. Like append() it is called in the list.

    # Let's add several elements at once
    alphabet = ['a', 'b', 'c']
    alphabet.extend(["f", "d", "g", "e"])
    print(f "Alphabet (confused): {alphabet} (length: {len(alphabet)})")

The above program will extend the initial list ['a', 'b', 'c'] 'by the letters' f', 'd', 'g' and 'e'. The variablealphabetafter theextend()function will have the value ['a', 'b', 'c', 'f', 'd', 'g', 'e'] '. If instead of extend() use append() the result would be quite different: ['a', 'b', 'c', ['f', 'd', 'g', 'e']] - one complete list would be inserted as the fourth element in thealphabet variable.

Sorting lists

Python provides two built-in functions to sort collections:

  • sort() and
  • sorted().

We use the sort() function when we want to sort items in a given list. The function is called in the list and sorts it in place - after it is executed, the old order of the elements is lost.

    alphabet.sort()
    print(f "Alphabet (sorted): {alphabet} (length: {len(alphabet)})")

We use the sorted () function when we want to sort elements of a given list without changing the same list - a new, sorted list will be returned, while the old one will remain intact.

    # Let's add several elements at once
    sorted_alphabet = sorted(alphabet)
    print(f "Alphabet (sorted): {sorted_alphabet}, alphabet (unsorted): {alphabet})")

Other list functions

To view all list functions, enter the command help (list) in the terminal.

  • .count(x) - counts the number of occurrences of the x element in the list, returns the valueint.
  • .index(x) - returns what index the first x value in the list is under (the first one, because the elements in the lists may repeat).
  • .insert(index, x) - places the element x under the indexindex in the list, the rest of the value is shifted accordingly.
  • .pop(index) - removes the item from the list from the given index and returns it (it can be assigned to a variable, for example).
  • .pop() - remove the last item from the list and return it (it can be assigned to a variable, for example).
  • .remove(x) - removes the first occurrence of x in the list.
  • .clear() - clears the entire list, removes all elements from it; at the end there is an empty list.
  • .reverse() - reverses the order in which items appear in the list, thus changing their indexes.

All of the above functions are called on list variables. They should be run using the dot operator.

Cutting lists

Letters, like inscriptions, can be cut into sublists in the same way:

    users = ["Alice", "Bob", "Chris", "John"]
    print(users)
    print(users [0: 3]) # first three items
    print(users [1: 2]) # ['Bob']
    print(users [: 2]) # ['Alice', 'Bob']
    print(users [1:]) # ['Bob', 'Chris', 'John']

Dictionary

Dictionaries are variables of type dict, which require { and } characters to create. The dictionary has similar properties to the list, it is:

  • modifiable,
  • dynamic
  • and can be nested (dictionaries in dictionaries).

The difference between these two collections is that the lists allow access to their elements through the index, and the dictionaries through the key.

A dictionary is a data structure that is generally known as an associative array. The dictionary consists of a set of key-value pairs, where each pair maps the key to its associated value. Although the dictionaries can be expanded and changed, the keys must be non-modifiable types (e.g. numbers, text, Boolean values).

Dictionary definition

    # Create an empty dictionary
    phonebook = {}

    # Add two items
    phonebook["John"] = 111111111
    phonebook["Jack"] = 222222222

    print(phonebook)
    print(phonebook["Jack"])

    # Definition of the finished dictionary
    phonebook2 = {
        "John": 111111111,
        "Jack": 222222222
    }

Reference to an element in the dictionary is almost the same as in the case of lists, with the key value given in square brackets instead of the index.

In dictionaries, a colon separates the key-value pair.

Deleting items from the dictionary

To remove items from the dictionary, use:

  • the function .pop(),
  • the keyword del.

Here is an example of removing items 111111111 and 222222222 from dicta:

    phonebook = {"John": 111111111, "Jack": 222222222}

    # We remove items
    del phonebook["John"]
    phonebook.pop( "Jack")

    print(phonebook)

del deletes the value from the dictionary forever. pop() returns the item after deleting, so you can assign it to a variable.

Extracting values ​​from the dictionary

The .get() function of the dictionary returns the value under the key given as the parameter. If no such key exists, None will be returned.

    letters = {"a": 1, "b": 2}
    print(letters.get("c")) # Prints None
    print(letters["c"]) # ERROR! Python will throw an exception.

The .get() function is helpful when you are not sure that a key will be available in the dictionary being analysed. An attempt to refer to a non-existent key in the dictionary through square brackets results in an error being returned.

We can further specify, giving as a second argument, the value that should be returned in case the key does not exist in the dictionary.

    print(letters.get("c", 0)) # Prints 0

Combining dictionaries

Instead of manually adding new key-values, the dictionary can be extended using pairs from another dicta. The .update() function is used for this. In case dictionaries have the same key, the value of the element is updated.

    letters_1 = {"a": 1, "b": 2}
    letters_2 = {"c": 3, "b": 0}
    print(letters_1.update(letters_2)) # Prints {"a": 1, "b": 0, "c": 3}

Tuple (tuple)

Tuples (tuple variables) are very similar to lists, the only differences are:

  • The unmodifiable tuples of a defined collection can no longer be changed.
  • The characters ( and ) are used for its definition, or alternatively decimal values ​​are given.

Definition of the tuple

    # Declaration of an empty tuple
    short_1 = ()

    # Short empty declaration
    short_2 = ("dog", "cat", 2000, 5.0, True)
    short_3 = "a", 2, "c", [1, 2, 3]

    # One-element short is defined by adding a comma to the value!
    short_4 = ("one_element",)

Short cut

    # Accessing item (s) short
    short_4 = (1, 10.5, False, None, "string")
    print(short_4[2]) # Prints False
    print(short_4[1: 3]) # Prints (10.5, False)

All other actions related to lists (adding elements, expanding tuples, removing elements, flipping the tupla) are not available for tuples. The only functions available are: count() and index() - they work the same way as for list variables.

Collection

Grouping objects into sets (set variables) can be useful in programming: if:

  • We want a collection that will not accumulate repeatable values.
  • We want to be able to quickly determine the elements present in two collections or elements available in one but not present in the other.

The collections are what we currently need.

Here are the features of sets:

  • Non-indexable and unordered collection.
  • Written with { and } characters.
  • An empty set is created using the set() command (the same {} defines an empty dictionary!).
  • Values ​​in the set do not repeat.
  • There is no access to elements, elements in the set do not have indexes.
  • The set itself can be modified, but the elements that it contains must be unmodifiable (numbers, strings, Boolean values, None).

Definition of the set and basic functions

    # Create a set
    animals = {"dog", "cat", "elephant"}

    # Add new item (equivalent append in the list)
    animals.add( "mouse")

    # Add several items at once (equivalent to extend in list)
    animals.update(["bird", "horse"])

    # Add the same item again
    animals.add("mouse")
    print(animals)

    # Remove item, Python will throw an error if it is not in the set
    animals.remove("cat")

    # Remove item, Python will NOT throw an error if it is not in the set
    animals.discard("cat")

    print(len(animals)) # len can also be used for sets

Harvest operations

As in mathematics, Python also provides the ability to perform more advanced operations on sets.

For example, the following operations are possible:

  • finding the common part of two collections,
  • finding the sum of two sets,
  • find a part that occurs in one but is not present in the other set.

Operations carried out for two sets with numerical values:

    set_1 = {1, 2, 3}
    set_2 = {2, 3, 4, 5, 6}
  • Finding the common part of the collection
    print(x1 & x2) # Display {2, 3}
    print(x1.intersection (x2)) # Will display {2, 3}
    print(x2.intersection (x1)) # Same as above

intersection

  • Finding the sum of collections
    print(x1 | x2) # Displays {1, 2, 3, 4, 5, 6}
    print(x1.union (x2)) # will display {1, 2, 3, 4, 5, 6}
    print(x2.union (x1)) # Same as above

union

  • Finding the difference of two sets
    print(x1 - x2) # Will display {1}
    print(x1.difference (x2)) # will display {1}
    print(x2.difference (x1)) # will display {4, 5, 6}

diff

Modifiable (mutable) and non-modifiable (immutable) types

Here is a short summary dividing variables into modifiable and non-modifiable:

Mutable The content of such variables can be modified without creating a new variable - saving memory, these collections can be really large, returning a new sequence each time could lead to memory problems.

  • list,
  • collection,
  • dictionary.

Immutable Variables of this type cannot be modified after creation, each time a new entity will be created.

  • int
  • float,
  • bool,
  • str.
  • tuple
  • frozenset.

Information extension and even more functions are available in official Python documentation.