NLP - C4W2 - TF/Python Question

Hi, so this is provided code in a section of the notebook we don’t have to write any code, so I think it is ‘okay’ to post:

image

Can someone please tell me what exactly is going on with the for _ in range(self.num_layers). I mean it is already contained within a list, and then, mysteriously there is this for-loop.

Yet no code to be in the loop comes after it. The list declaration just ends.

I am not sure what is going on here.

*Of note, this appears in the Encoder.

The for-statement is an iterator, so that you get a list that contains exactly self.num_layers of EncoderLayer() objects.

1 Like

So if I understand you here, it produces self.num_layers of the EncoderLayers specified above it ?

That seems a little weird. Why doesn’t the for statement come first ? And does this technique work for any Python list or is it one of those weird TF things ?

Python iterators can take a lot of different syntaxes.

It’s not a TensorFlow thing - TensorFlow’s Python API doesn’t have any unique aspects.

1 Like

K, thank you.

And just by ‘weird Tensorflow thing’, I mean another mentor helped me with that but, for ex, they implement an expected def call function for example, but it was not clear to me at the time where on Earth that was coming from.

It certainly isn’t def __call__.

1 Like

For additional context, the syntax you shared is called list comprehension in Python. It’s part of Python’s flair, it is more efficient than using a for loop.

1 Like

Thanks @lukmanaj-- Yes I am aware of list comprehension, but just have never seen it done this way before with the for-loop.

1 Like