-1

I am relatively new to Python, and I am not sure what exactly this statement does. I haven't been able to find anything with a syntax like this in my course books either. I assume it declares an array? but I am nit sure.

What exactly does this statement mean/do?

 G = {i: [] for i in range(len(l))}

(If anyone is able to explain it to me in Java equivalent, that would be easier as I know Java pretty well)

KSP
  • 3
  • 2

2 Answers2

0

It's a dictionary comprehension, so it'll create a dictionary mapping the ints 0-(N-1) where N is the length of the list to empty lists

>>> {index: list() for index in range(5)}
{0: [], 1: [], 2: [], 3: [], 4: []}
ti7
  • 16,375
  • 6
  • 40
  • 68
-1

This thing in python is called dict-comprehension. i.e, we can write any logic in a single line and return a dict.

In your case {i: [] for i in range(len(l))}, it is equivalent to this;

G = {}
for i in range(len(l)):
    G[i] = []
Irfan wani
  • 4,084
  • 2
  • 19
  • 34