Search code examples
pythonlistlist-comprehensionfactors

Python List Comprehension Reverseal


So I wrote a Python statement takes a variable named n and creates a list of n's factors smallest to largest. I would I rewrite this statement to reverse the list to output it as largest to smallest?

Here is the statement:

factors = [x for x in range(2,n) if n % x == 0]

Solution

  • Just use reverse.

    >>> test = [1,2,3,4]
    >>> test.reverse()
    >>> test
    [4, 3, 2, 1]