How to loop 'for' in 1 line?

Asked

Viewed 1,292 times

7

The following code did not work:

rank = [1, 2, 3, 4]

print(rank[c] for c in range(4))

If you can make use of for in a row would like to know.

  • 1

    André, would like to see List Comprehensions: https://docs.python.org/3/tutorial/datastructures.html#Tut-listcomps, for example: https://repl.it/@Dadinel/Happylightgreenportablesoftware

  • 1

    Thank you for your help.

3 answers

10


Depends much what you want to do, and maybe you don’t even need the for.

Do you want to simply print the list elements? So why not just do print(rank)? All right that will print [1, 2, 3, 4] and you may want the elements to be separated by some other character, and without the brackets. If that’s the case, you can just do so:

print(*rank) # 1 2 3 4

# ou
print(' '.join(map(str, rank))) # 1 2 3 4

The first case uses the syntax of unpacking: the asterisk says that each item on the list rank must be passed as a parameter to print, that is, in this case it is the same as doing print(1, 2, 3, 4). The second case uses join to join the elements of the list, separating them by space (the disadvantage is that I needed to use map to turn numbers into strings, otherwise join makes a mistake).

If you want to change to print each element on a line (you can’t tell if that’s the intention), just switch to:

print(*rank, sep='\n')

# ou
print('\n'.join(map(str, rank)))

Or do you want to much wear a for, anyway? Honestly, for what looks like be your need (just want to print the list elements), no need to complicate. One of the answers (deleted) suggested to do [print(c) for c in rank], Which is a bit of a scam, in my opinion. That’s because, thanks to the brackets around the expression, you’re creating a list - and it’s created for nothing, because it’s not stored in any variable and it’s only there for the print be called several times. But if so, why not use a for simple?

for n in rank:
    print(n)

"Ah, but it’s not on a line."

So what? What you should be aiming for is to write clear, uncomplicated code. Often the attempt to make it shorter can end up making it worse. Smaller code is not necessarily better. And number of lines, especially in a simple case like this, is such a secondary factor that it shouldn’t even be a concern.

I know it can often seem "cool" to use a "smart" language feature (such as such list comprehensions they suggested), but I also think it’s important to understand that each tool has its use, and you don’t always need to use them. If it’s just to print out the list, I don’t think you need it. And wanting to force some use just to "stay all in one line" seems to me a wrong use of the resource.


If you just want to do the "for in a row, "You can also cheat:

for n in rank: print(n)

Yeah, that’s equivalent to:

for n in rank:
    print(n)

But it’s on a line :-) sorry, I couldn’t resist

  • Thank you for your help.

5

To have the for in a row, just do:

print([rank for rank in range(4)])

You need to put it between the "[" and "]" brackets to work, otherwise error will occur.

It is also possible to apply filters, for example:

print([rank for rank in range(4) if rank % 2 == 0])

Will output only the numbers pares.

In python it’s called list comprehensions

3

If really necessary, yes to implement not only "1" only "for", but also "2" or "3" in one line only.

For this we must use the concepts of List Comprehesions.

If the structure does not need to be used "for" we can use the function "map", like the next three examples.

1st Example:

By working with the same values you used, we can capture them on the keyboard to be entered into the list and then display them. For this we must implement the following code...

lista = list(map(int, input().split()))
print(lista)

In the first line of this code we implement a list and, within it, we map the insertion of "n" integer values separated by a space. In this code, we will capture all the values from the keyboard (typing all of them in the same line, separating them by just one space). In this way, we can implement a list with an undefined number of values, which can be either integer (int), real (float) or strings (strings). To change the type of variable just change its type, for example...

2nd Example:

lista = list(map(float, input().split()))
print(lista)

In this example we replace the type "int" for "float".

3rd Example:

lista = list(map(str, input().split()))
print(lista)

In this case, we swap the type of numeric variable for string. The algorithm will continue to work.

Now, if you really want to implement a lot of instruction "for" in just one line, you can check the other examples.

4th Example:

lista = [item for item in range(1, 5)]
print(lista)

With this algorithm you can implement a list of integer numbers starting from "1" until "5 - 1", that is to say of "1" until "4".

5th Example:

lista = [item**2 for item in range(10)]
print(lista)

This algorithm creates and displays a list of "10" perfect first squares.

6th Example:

lista = [item**3 for item in range(20)]
print(lista)

This algorithm creates and displays a list of "20" perfect first cubes.

7th Example:

lista = [numero for numero in range(0, 21) if numero % 2 == 0]
print(lista)

This algorithm creates and displays a list of "primeiros" even numbers between "0" and "20".

8th Example:

lista = [numero for numero in range(0, 31) if numero % 2 != 0]
print(lista)

This algorithm creates and displays a list of "primeiros" odd numbers between "0" and "30".

9th Example:

lista = [numero for numero in range(0, 101) if numero % 5 == 0 if numero % 6 == 0]
print(lista)

This algorithm creates and displays a list of numbers between "0" and "100", which are simultaneously "múltiplos" of "5" and "6".

10th Example:

lista = ['1' if numero % 4 == 0 else '0' for numero in range(20)]
print(lista)

This algorithm creates and displays a list of 20 elements that contains "1" where a number is multiple of 4, and "0", otherwise.

11th Example:

When necessary, we can also insert "2" structures "for" in a single line. This occurs when we want to obtain a list formed by the combinations of the elements of the other "two" lists, when the elements are different...

lista = [(x, y) for x in range(1, 4) for y in range(1, 5) if x != y]
print(lista)

In this case, we obtain a list, in which the elements of it are tuples (bounded by parentheses).

12th Example:

If we want to calculate the value of "pi" with 1, 2, 3, 4, 5, ... , n, decimals we can use the following algorithm...

from math import pi
lista = [str(round(pi, i)) for i in range(1, 6)]
print(lista)

From this algorithm we obtain the value of "pi" calculated with up to "5" decimal places.

13th Example:

If this is the case, we can also enter "3" structures "for" in the same line. This occurs when we want to obtain a list formed by the combinations of the elements of the other "three" lists, when the elements are different...

lista = [(x, y, z) for x in range(1, 3) for y in range(1, 4) for z in range(1, 4) if x != y != z]
print(lista)

14th Example:

If we want to put together a list of "logaritmos neperianos" of each element of another list we can use the following algorithm...

from math import log

lista = [1, 3, 5, 6, 8, 12]
resultado = [round(log(item), 5) for item in lista]
print(resultado)

15th Example:

If we want to put together a list of temperatures in degrees "celsius" of a list of temperatures in degrees "fahrenheit", we can use the following algorithm...

fahrenheit = [32, 46, 55, 68, 73, 94, 98, 106]

celsius = [round(((5 * (item - 32)) / 9), 1) for item in fahrenheit]
print(celsius)

16th Example:

If we want to build a list consisting of the values of "senos" and "cossenos" of the angles, whose values are in another list, we can use the following algorithm...

from math import sin, cos, radians

angulos = [0, 10, 20, 30, 45, 60, 90]
senos_cossenos = [(round(sin(radians(item)), 3), round(cos(radians(item)), 3)) for item in angulos]
print(senos_cossenos)

17th Example:

If we wish to find the "raizes quadradas" of the values from another list, we can use the following code...

from math import sqrt

valores = [2, 4, 9, 10, 16, 20, 25, 36, 49, 64, 81, 100, 121]
raiz_quadrada = [round(sqrt(item), 2) for item in valores]
print(raiz_quadrada)
  • 1

    Thank you for your help.

  • 3

    Ok. We’re here to share quality content.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.