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
🌐
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.
🌐
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.
🌐
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.
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.

🌐
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.
Find elsewhere
🌐
Platzi
platzi.com › tutoriales › 4227-python-fundamentos › 31662-python-tutorial-for-loop-with-list-comprehensions
Python Tutorial - For Loop with List Comprehensions
List comprehensions provide a concise and readable way to create new lists by applying an expression to each item in an existing list (or any iterable). It’s a very Pythonic way to handle list transformations. In a list comprehension, you typically include a for loop and an optional if condition inside square brackets.
🌐
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
January 4, 2018 -

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 ...
🌐
Sololearn
sololearn.com › en › Discuss › 1684765 › python-array-for-loop
Python array for loop | Sololearn: Learn to code for FREE!
Came across this for loop in a python challenge. I'm still trying to understand exactly what it's doing. Any help? arr = [(5,8,0), (2,4)] sum = [] for x, *y in arr:
🌐
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.