What is a list with curly brackets in python?

Curly braces create dictionaries or sets. Square brackets create lists.

They are called literals; a set literal:

aset = {'foo', 'bar'}

or a dictionary literal:

adict = {'foo': 42, 'bar': 81}
empty_dict = {}

or a list literal:

alist = ['foo', 'bar', 'bar']
empty_list = []

To create an empty set, you can only use set().

Sets are collections of unique elements and you cannot order them. Lists are ordered sequences of elements, and values can be repeated. Dictionaries map keys to values, keys must be unique. Set and dictionary keys must meet other restrictions as well, so that Python can actually keep track of them efficiently and know they are and will remain unique.

There is also the tuple type, using a comma for 1 or more elements, with parenthesis being optional in many contexts:

atuple = ('foo', 'bar')
another_tuple = 'spam',
empty_tuple = ()
WARNING_not_a_tuple = ('eggs')

Note the comma in the another_tuple definition; it is that comma that makes it a tuple, not the parenthesis. WARNING_not_a_tuple is not a tuple, it has no comma. Without the parentheses all you have left is a string, instead.

See the data structures chapter of the Python tutorial for more details; lists are introduced in the introduction chapter.

Literals for containers such as these are also called displays and the syntax allows for procedural creation of the contents based of looping, called comprehensions.

Curly brace scopes, autovivification, and other methods for writing better code

Photo by Josh Kahen on Unsplash

Python will always find something to surprise us with — there are simply far too many brilliant features crammed into the language. Fortunately, this means we never run out of things to learn.

Over time I’ve built up a habit of making a note of every new feature I stumble upon in Python. Mostly they’re exciting but come with pretty narrow use-cases.

Other times, however, I stumble upon a feature that is genuinely very widely applicable — and often, it will change the way I code. I keep track of these with a list, and this article covers five of my favorite features from that list.

Get Method for Dictionaries - no more KeyErrors
Tree Datatypes - or autovivification
Advanced List Indexing - [::3]?
Decorator Functions - those @ things
Denote Scopes with Braces - not whitespace (my favorite feature)

Get Method for Dictionaries

The dictionary get method performs the same operation as the more common dict[key] syntax with one significant difference — we don’t throw an error if the key does not exist in our dictionary:

dictionary = {
'one': 1,
'two': 2
}
dictionary['three']

[Out]: KeyError: 'three'

With get

dictionary.get('three')

[Out]: None

Rather than returning a KeyError, the get method returns None.

We can take it one step further by specifying a value to return if the key does not exist with the get method’s second argument:

dictionary.get('three', False)

[Out]: False

dictionary.get('three', "doesn't exist")

[Out]: 'doesn't exist'

Finally, if you know the contents of your dictionary — don’t use get it’s slower! (thanks Petru)

Tree Datatypes

A tree datatype looks like this:

What is a list with curly brackets in python?

Tree representation of words in a sentence and their respective parts of speech (PoS) tags. Source: author.

It represents a hierarchical tree structure with a root value at the top-most layer, which branches down into child nodes. Each child node has one parent node, and each parent node may have one or more child nodes.

Now, our representation in Python will be very similar to a nested dictionary, which we would build like this:

tree = {
'carnivora': {
'canis': {
'c.lupus': 'c.l.familiaris'
},
'felis': 'f.catus'
}
}

Here we need to define a new dictionary for every single child node, one step at a time.

It’s slow, messy, and prone to error — imagine this for a simple five-layer tree where each parent node has just two child nodes.

Fortunately, we can build our tree datatype with just this:

Now, rather than defining each child dictionary as we go, we can build out entire branches immediately:

tree = Tree()
tree['carnivora']['canis']['c.lupus'] = 'c.l.familiaris'
tree['carnivora']['felis'] = 'f.catus'
print(tree)
[Out]: {
'carnivora': {
'canis': {
'c.lupus': 'c.l.familiaris'
},
'felis': 'f.catus'
}
}

What is a list with curly brackets in python?

Scientific classification tree of man’s best friend and those other things people like. Photo by Jamie Street on Unsplash (left), Photo by Kari Shea on Unsplash (right).

This method has a name, autovivification — the automatic creation of new arrays and hashes every time an undefined value is dereferenced.

Another single line implementation (excluding the import) can be found here.

Advanced List Indexing

Steps

There are several unknown list slicing methods, despite being useful. The first of those is the use of steps:

x = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
x[::2]

[Out]: [0, 4, 8, 12, 16]

The syntax we are using here is list[start:end:step] — because we leave start and end empty, we iterate from the very start to the very end of the list, with a step of 2.

x[3:8:2]

[Out]: [6, 10, 14]

Named Slices

The following advanced list slicing method is called named slices. Here, we assign a slice to a variable, like so:

named_slice = slice(5, None)  # this is equivalent to [5:]

We can then apply this named slice to any list.

x[named_slice]

[Out]: [10, 12, 14, 16, 18]

The syntax we are using here uses the same start, end, step pattern — slice(start, end, step). We can rewrite x[3:8:2] like this:

new_slice = slice(3, 8, 2)
x[new_slice]

[Out]: [6, 10, 14, 18]

Decorator Functions

A decorator function is one of those weird @func_name things I’m sure many of us have seen — in particular, the Flask library makes heavy use of them.

They’re surprisingly simple to understand and incredibly useful. Decorators simply allow us to modify the behavior of a function without explicitly modifying our function.

For example, we can define a pointless function that will iterate through a range, eventually returning the printing the final value multiplied by two:

def pointless():
for i in range(20000000):
x = i*2
print(x)

[Out]: 39999998

This function will do nothing but take a long time to run — but that is what we want. We are going to time the runtime of this function using a decorator function.

The decorator is defined just like any normal function:

def timer(func):
def wrapper():
start = datetime.datetime.now()
func()
runtime = datetime.datetime.now() - start
print(runtime)
return wrapper

We can then use that weird @ syntax when defining our pointless function to inherit the timer behavior.

@timer
def pointless():
for i in range(20000000):
x = i*2
print(x)
pointless()[Out]: 39999998
0:00:01.220755 <-- this is returned from our decorator

We can also use multiple decorators. Let’s define another called repeat that will iterate over any given function twice.

def repeat(func):
def wrapper():
for i in range(2):
func()
print(i)
return wrapper

If we now apply both @timer and @repeat decorators to our pointless functions we will get this:

@timer
@repeat
def pointless():
for i in range(20000000):
x = i*2
print(x)
pointless()[Out]: 39999998
0 <-- printed in @repeat
39999998
1 <-- @repeat again
0:00:01.220755 <-- printed from @timer

Here we have wrapped pointless into @repeat and the resulting function into @timer — like some weird Frankenstein’s monster of Python functions.

The decorators we have used here are simple toy examples. We can do a lot more with decorators — I would recommend taking a look at these articles/resources:

  • Primer on Python Decorators (a free, comprehensive article on decorators)
  • Fluent Python, Luciano Ramalho (lots of Python — not just decorators)

Denote Scopes with Braces

Easily my favorite advanced feature in Python, rather than relying on whitespace to denote scopes (boring) — we can use curly braces!

We import the functionality from the __future__ library:

from __future__ import braces

And off we go!

That’s five uncommon, but super handy features in Python. A couple of honorable mentions that I’d like to leave with you to try out:

>>> import this
>>> import antigravity
>>> hash(float('inf'))

I’ve put together a small GitHub repo with examples of all of the above features, and more, here. Check it out for code snippets — and of course, feel free to add your own!

If you have any suggestions or questions, feel free to reach out via Twitter or in the comments below. Or, if you’d like more content like this, I post on YouTube too.

Thanks for reading!

What does {} mean in Python?

In languages like C curly braces ( {} ) are used to create program blocks used in flow control. In Python, curly braces are used to define a data structure called a dictionary (a key/value mapping), while white space indentation is used to define program blocks.

What does {} brackets mean in Python?

[] brackets are used for lists. List contents can be changed, unlike tuple content. {} are used to define a dictionary in a "list" called a literal.

What is the {} used for?

In writing, curly brackets or braces are used to indicate that certain words and/or sentences should be looked at as a group.

What are {} brackets called?

Curly brackets {} Curly brackets, also known as braces or curly braces, are rarely used in formal writing and are more common in other fields such as science, math, and computing. Some style guides will allow them to be used for one specific purpose: grouping together a set.