Did not understand the code with conversion of the loop to a list in python

3622 views
1

I am a novice in python, and got this code:

``````versions = [x.name[len(name):] for x in nlist
if (x.name.startswith(name) and is_number(x.name[len(name):]))]
``````

I understand that the for loop is concatenated into the versions list but I do not understand the assignment:

``````[x.name[len(name):]
``````

What is `name`? It's defined externally. What about `nlist`?

@MadPhysicist that doesn't matter here too much, as he is simply asking about the syntax of the list comprehension. (although it would if he was trying to provide a MVCE) :)

Sure. I'm promoting him to ask clearer questions, but not insisting on it.

11

I'll expand the whole code, then go through it

``````versions = [x.name[len(name):] for x in nlist
if (x.name.startswith(name) and is_number(x.name[len(name):]))]
``````

is equivilent to

``````versions = []
for x in nlist:
if (x.name.startswith(name) and is_number(x.name[len(name):])):
versions.append(x.name[len(name):])
``````

as for what

``````x.name[len(name):]
``````

means, it means to take from x.name, the characters starting at the index which is equal to `len(name)` (the length of name), to the end of the `x.name`

so in a simpler example, say I have a list

``````my_list = [1, 2, 3, 4, 5]
``````

and I do

``````my_list[2:]
``````

then this would return

``````[3, 4, 5]
``````

which is the same as from the 2th element to the end.

I hope this helps. If you want to learn more about python slice notation, I can recommend this other SO question: Understanding Python's slice notation

posted this
13

In python if `x` is a list and `i` is an index (an integer).

``````x[i:]
``````

means "all item in `x` starting at index `i` all the way to the end"

You can also have

``````x[i:j]
``````

"all item in `x` starting at index `i` all the way to, but not including `j`"

``````x[:j]
``````

"all item in `x` starting at beginning all the way to, but not including `j`"

``````y = x[:]
``````

"copy all elements of x in a new list and assign it to y"

There are more I'd suggest looking up list properties in Python.

posted this