I'm trying to learn neat pythonic ways of doing things, and was wondering why my for loop cannot be refactored this way:
The inner loop runs on a range starting 1 to 11 that is 10 numbers, and both these for loops were running on one single of executable code to print the multiplication table of number 10. Frequently Asked Python Interview Questions & Answers. Dec 1, 2015 - List comprehensions are a tool for transforming one list (any iterable. This new list (line 6); Copy the for loop line, excluding the final: (line 4).
I tried replacing the for loop with:
But it doesn't work. The
for v in vm:
loop evicts numbers from vm
based on when they come next in q
.Will
WillWill2,83955 gold badges2020 silver badges4141 bronze badges
4 Answers
What you are using is called a list comprehension in Python, not an inline for-loop (even though it is similar to one). You would write your loop as a list comprehension like so:
When using a list comprehension, you do not call
iCodezlist.append
because the list is being constructed from the comprehension itself. Each item in the list will be what is returned by the expression on the left of the for
keyword, which in this case is q.index(v) if v in q else 99999
. Incidentially, if you do use list.append
inside a comprehension, then you will get a list of None
values because that is what the append
method always returns.![One Line For Loop Python One Line For Loop Python](/uploads/1/2/5/8/125846580/302119100.png)
114k2424 gold badges224224 silver badges229229 bronze badges
your list comphresnion will, work but will return list of None because append return None:
demo:
better way to use it like this:
HackaholicHackaholic12.9k22 gold badges3131 silver badges4646 bronze badges
you can use enumerate keeping the ind/index of the elements is in vm, if you make
vm
a set you will also have 0(1)
lookups:![Loops Loops](/uploads/1/2/5/8/125846580/455795931.png)
138k1414 gold badges137137 silver badges212212 bronze badges
Output:
Instead of using
append()
in the list comprehension you can reference the p as direct output, and use q.index(v)
and 99999
in the LC.Not sure if this is intentional but note that
q.index(v)
will find just the first occurrence of v
, even tho you have several in q
. If you want to get the index of all v
in q
, consider using a enumerator
and a list of already visited indexes
Something in those lines(pseudo-code):
f.rodriguesf.rodrigues1,97322 gold badges1616 silver badges4040 bronze badges