The "brackets" in your example constructs a new list from an old one, this is called list comprehension.

The basic idea with [f(x) for x in xs if condition] is:

def list_comprehension(xs):
    result = []
    for x in xs:
        if condition:
            result.append(f(x))
    return result

The f(x) can be any expression, containing x or not.

Answer from folkol on Stack Overflow
Discussions

For loop in python using brackets - Stack Overflow
As per Python documentation, the square brackets are essentially ignored in assignments and loop constructs. More on stackoverflow.com
๐ŸŒ stackoverflow.com
dictionary - Python: for loop in index assignment - Stack Overflow
While working through the awesome book "Programming Collective Intelligence", by Toby Segaran, I've encountered some techniques in index assignments I'm not entirely familiar with. Take this for e... More on stackoverflow.com
๐ŸŒ stackoverflow.com
October 14, 2011
Brackets after range() method in for loop?
What is this doing, exactly? Making up for the fact that the author doesn't know how to use range() /s More on reddit.com
๐ŸŒ r/learnpython
17
10
September 4, 2021
list - Using python for loop inside brackets - Stack Overflow
Communities for your favorite technologies. Explore all Collectives ยท Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
HowDev
how.dev โ€บ answers โ€บ how-can-we-loop-through-a-list-using-a-for-loop-in-python
How can we loop through a list using a for loop in Python?
To iterate through a list in Python, use a for loop to print each element individually until all elements are processed.
๐ŸŒ
TutorialBrain
tutorialbrain.com โ€บ home โ€บ square brackets python for loop
square brackets python for loop Archives โ€” TutorialBrain
This is a complete Brackets tutorial for Beginners, Intermediate Level Programmers or Experienced Developers who are using other code editors and want to switch to Brackets.
๐ŸŒ
Dataquest
dataquest.io โ€บ blog โ€บ tutorial-advanced-for-loops-python-pandas
Tutorial: Advanced Python for Loops โ€“ Dataquest
March 11, 2025 - We'll skip lists since those have been covered in the previous tutorial; if you need further review, check out the introductory Python for loops tutorial or Dataquest's interactive lesson on lists and for loops. Tuples are sequences, just like lists. The difference between tuples and lists is that tuples are immutable; that is, they cannot be changed (learn more about mutable and immutable objects in Python). Tuples also use parentheses instead of square brackets.
Top answer
1 of 6
15
[str(wi) for wi in wordids]

is a list comprehension.

a = [str(wi) for wi in wordids]

is the same as

a = []
for wi in wordids:
    a.append(str(wi))

So

createkey='_'.join(sorted([str(wi) for wi in wordids]))

creates a list of strings from each item in wordids, then sorts that list and joins it into a big string using _ as a separator.

As agf rightly noted, you can also use a generator expression, which looks just like a list comprehension but with parentheses instead of brackets. This avoids construction of a list if you don't need it later (except for iterating over it). And if you already have parentheses there like in this case with sorted(...) you can simply remove the brackets.

However, in this special case you won't be getting a performance benefit (in fact, it'll be about 10 % slower; I timed it) because sorted() will need to build a list anyway, but it looks a bit nicer:

createkey='_'.join(sorted(str(wi) for wi in wordids))

normalizedscores = dict([(u,float(l)/maxscore) for (u,l) in linkscores.items()])

iterates through the items of the dictionary linkscores, where each item is a key/value pair. It creates a list of key/l/maxscore tuples and then turns that list back into a dictionary.

However, since Python 2.7, you could also use dict comprehensions:

normalizedscores = {u:float(l)/maxscore for (u,l) in linkscores.items()}

Here's some timing data:

Python 3.2.2

>>> import timeit
>>> timeit.timeit(stmt="a = '_'.join(sorted([str(x) for x in n]))", setup="import random; n = [random.randint(0,1000) for i in range(100)]")
61.37724242267409
>>> timeit.timeit(stmt="a = '_'.join(sorted(str(x) for x in n))", setup="import random; n = [random.randint(0,1000) for i in range(100)]")
66.01814811313774

Python 2.7.2

>>> import timeit
>>> timeit.timeit(stmt="a = '_'.join(sorted([str(x) for x in n]))", setup="import random; n = [random.randint(0,1000) for i in range(100)]")
58.01728623923137
>>> timeit.timeit(stmt="a = '_'.join(sorted(str(x) for x in n))", setup="import random; n = [random.randint(0,1000) for i in range(100)]")
60.58927580777687
2 of 6
3

Let's take the first one:

  1. str(wi) for wi in wordids takes each element in wordids and converts it to string.
  2. sorted(...) sorts them (lexicographically).
  3. '_'.join(...) merges the sorted word ids into a single string with underscores between entries.

Now the second one:

normalizedscores = dict([(u,float(1)/maxscore) for (u,l) in linkscores.items()])
  1. linkscores is a dictionary (or a dictionary-like object).
  2. for (u,l) in linkscores.items() iterates over all entries in the dictionary, for each entry assigning the key and the value to u and l.
  3. (u,float(1)/maxscore) is a tuple, the first element of which is u and the second element is 1/maxscore (to me, this looks like it might be a typo: float(l)/maxscore would make more sense -- note the lowercase letter el in place of one).
  4. dict(...) constructs a dictionary from the list of tuples, where the first element of each tuple is taken as the key and the second is taken as the value.

In short, it makes a copy of the dictionary, preserving the keys and dividing each value by maxscore.

Find elsewhere
๐ŸŒ
University at Buffalo
math.buffalo.edu โ€บ ~badzioch โ€บ MTH337 โ€บ PT โ€บ PT-lists.html
Lists, ranges and โ€œforโ€ loops โ€” MTH 337
Python for loops provide a way to iterate (loop) over the items in a list, string, or any other iterable object, executing a block of code on each pass through the loop.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 60727590 โ€บ using-python-for-loop-inside-brackets
list - Using python for loop inside brackets - Stack Overflow
Actually I encounter one code today which is shown below: def solution(ar,n): d={i: ar[i] for i in range(n)} for i in range(n-1): for j in range(i+1,n-1): if(ar[i]+ar[j...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ for loops with curly brackets -- please explain
r/learnpython on Reddit: For Loops with Curly Brackets -- Please explain
December 31, 2017 -

I am trying to understand this code. I understand that first for loop is iterating over the comments using the message column. However, why is a second for loop required and what do the curly braces do?

   for comment in comments[' Message']:
               s = sentiment.polarity_scores(comment)
               for k in sorted(s):
               print('{0}: {1}, '.format(k,s[k]))
   print(comment)
๐ŸŒ
Runestone Academy
runestone.academy โ€บ ns โ€บ books โ€บ published โ€บ fopp โ€บ Iteration โ€บ TheforLoop.html
7.2. The for Loop โ€” Foundations of Python Programming
name in this for statement is called the loop variable or, alternatively, the iterator variable. The list of names in the square brackets is the sequence over which we will iterate.
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ stable โ€บ reference โ€บ arrays.nditer.html
Iterating over arrays โ€” NumPy v2.4 Manual
The iterator object nditer, introduced ... This page introduces some basic ways to use the object for computations on arrays in Python, then concludes with how one can accelerate the inner loop in Cython....
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ gloss_python_array_loop.asp
Python Loop Through an Array
Python Examples Python Compiler ... Bootcamp Python Certificate Python Training ... You can use the for in loop to loop through all the elements of an array....
๐ŸŒ
Projectpython
projectpython.net โ€บ chapter07
Lists and for-loops - Project Python
You can type a list in using brackets and commas. When the Python interpreter reaches the brackets, Python allocates space in memory for the items in the list. Of course, usually thereโ€™s not much point in just printing out a list created this way; weโ€™d like to be able to refer to the list ...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 70567743 โ€บ python-for-loop-in-brackets-vs-parenthesis
Python for-loop in brackets vs parenthesis - Stack Overflow
So the first one(A) is in square brackets and the other one(B) is in "normal" brackets. Where is the difference between them, and which one is perferably better in this kind of case. ... One's a list comprehension, the other a generator expression. In this case they're both pointless, because you don't do anything inside the loop!
๐ŸŒ
Codingem
codingem.com โ€บ home โ€บ python for loopsโ€”a complete guide & useful examples
Python For Loopsโ€”A Complete Guide & Useful Examples
December 4, 2022 - A list of useful for loop examples in python. Learn how to loop your code like a pro with beginner-friendly examples and explanations.
๐ŸŒ
SheCodes
shecodes.io โ€บ athena โ€บ 2453-how-to-use-square-bracket-syntax-in-python
[Python] - How to Use Square Bracket Syntax in Python - | SheCodes
Output: Online Store โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€” Product(s) Price Item 1 200.0 Item 2 Item 3 Combo 1 (Item 1 + 2) Combo 2 (Item 2 + 3) Combo 3 (Item 1 + 3) Combo 4 (Item 1 + 2 + 3) โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€” For delivery contact 98764678899 ยท catalog item combo gift pack discount function code ... John R. Stalling's folding method in python