0

In this simple python example:

arr = [1,2,3,4,5]
for n in arr: 
    s = str(n)
    print(s) 

What I want to write is a code somehow similar to [str(n) for n in arr] but in the following format:

arr = [1,2,3,4,5]
for str(n) as s in arr: 
    print(s) 

I basically want to include s=str(s) inside for statement. Is the any handy way to do so in python?

DragonKnight
  • 1,375
  • 1
  • 16
  • 27
  • 2
    What result to you expect exactly ? The list comprehension is a way to store elements not print them. Just do `for n in arr: print(n) ` no need to pass to `str` – azro Apr 04 '20 at 09:14
  • The first example is fine, but you could just use `print(n)` directly. The second example with the list comprehension is also just fine. The third example doesn’t make sense, though. – mkrieger1 Apr 04 '20 at 09:15
  • 1
    Can you clarify what your goal is? Do you want to convert the list in place, convert the element in the for loop, or just print the values as strings? – MisterMiyagi Apr 04 '20 at 09:24
  • Your desired format is very obviously a syntax error. Just to be clear: You want to *remove* the single line ``s = str(s)``, and still want `s` to be a ``str`` regardless of its initial type? – MisterMiyagi Apr 06 '20 at 13:52
  • 1
    It seems you are looking for the "walrus operator". See https://stackoverflow.com/questions/50297704/syntax-and-assignment-expressions-what-and-why – mkrieger1 Apr 06 '20 at 13:55
  • so it will be `for s:=str(s) in arr`? – DragonKnight Apr 06 '20 at 23:06

2 Answers2

1

There are at least two ways:

map:

arr = [1,2,3,4,5]
for s in map(str, arr): 
    print(s)

generator comprehensions:

arr = [1,2,3,4,5]
for s in (str(n) for n in arr):
    print(s) 
Community
  • 1
  • 1
L3viathan
  • 23,792
  • 2
  • 46
  • 64
1

You don't need to use str at all. The print function converts its arguments to strings automatically.

So you can simply use:

for n in arr:
    print(n)

no matter what n is.

Reference: https://docs.python.org/3/library/functions.html#print

mkrieger1
  • 10,793
  • 4
  • 39
  • 47