1

Im very new to Python and finding it very different to anything ive encountered before coming from the PHP realm.

Background:

Ive searched SO and learned that the differences between:

x = [] and x{} is that the brackets will create a list and the curly braces is for creating a series. What I could not find however is an explination for the following

Question

Why does this piece of code use braces inside a list with brackets like so:

context.modules[(stock, length)] = 0

Why the braces inside the list?

And then as a "bonus help" if I may why set it to 0 (although that's probably out of scope of question)

Fullcode:

context.modules = {}
    for stock in context.stock_list:
        for length in context.channels:
            context.modules[(stock, length)] = 0
cs95
  • 379,657
  • 97
  • 704
  • 746
Timothy Coetzee
  • 5,626
  • 9
  • 34
  • 97

2 Answers2

1

Your context.modules is not a list, it's a python dictionary (map in most other languages)

So, when you're doing this:

context.modules[(stock, length)] = 0

You're basically creating a key, value pair in the dictionary, with key as a tuple of (stock, length) and value as 0.

Considering

stock = 2 and length = 5

your context.modules after the above assignment, will look like this:

>>> context.modules
{(2, 5): 0}
Ashish Ranjan
  • 5,523
  • 2
  • 18
  • 39
1

This is a dictionary, as you understand:

In [463]: dct = {'a' : 1}

In [464]: dct['a']
Out[464]: 1

It has one key-value entry. The key is a str type. strs are allowed to be keys for a dictionary because they can be hashed because they are immutable and their objects yield a unique, unchanging hash value which the dictionary uses to index the object for fast access.

Similarly, ints, floats, bools, basically anything that is immutable may be a key. This includes tuples, but not structures such as lists, sets and dicts.

Now, here's a tuple:

In [466]: x = (1, 2) 

x can be used as the key in a dictionary.

In [469]: d = {x : 5}

In [470]: d
Out[470]: {(1, 2): 5}

To access the value associated with the tuple, you'd index with it:

In [471]: d[(1, 2)]
Out[471]: 5

This is the basic meaning behind that syntax you ask about. It is interesting to note that the parenthesis are optional:

In [472]: d[1, 2]
Out[472]: 5

This is because the parenthesis do not demarcate a tuple, but the comma , does.

cs95
  • 379,657
  • 97
  • 704
  • 746