1

I'm pretty new to programming and python.

As far as I know, for the initialization of the set function you use set() for an empty set, and { ... } to initialize elements as a set. In an example code, I saw set[X]. What is the meaning of the square brackets used in set?

This is the example code:

def example_function(x: set[A], y: set[B]) -> set[tuple[A, B]]:
    res = set()
    for i in x:
        for j in y:
            res.add((i, j))
    return res
EnesK
  • 93
  • 6

2 Answers2

1

It's a type hint, in this example, we use type hint For collections, the type of the collection item is in brackets.

Example:

# Python 3.9
# For collections, the type of the collection item is in brackets
int_list: list[int] = [1]
int_set: set[int] = {6, 7}

# Python 3.8 and earlier, the name of the collection type is
# capitalized, and the type is imported from 'typing'

from typing import List, Set, Dict, Tuple, Optional

int_list: List[int] = [1]
int_set: Set[int] = {6, 7}
Dyn4sty
  • 166
  • 4
0

This is just a parameterising the functions and variable annotations to say that the function needs two arguments, namely x and y which are of type set(build from A and B respectively) and it returns back a set consisting of tuples built by mixing set[A] set[B]

DhakkanCoder
  • 794
  • 3
  • 15