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?

6
  • 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 Commented Apr 4, 2020 at 9: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. Commented Apr 4, 2020 at 9: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? Commented Apr 4, 2020 at 9: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? Commented Apr 6, 2020 at 13:52
  • 1
    It seems you are looking for the "walrus operator". See stackoverflow.com/questions/50297704/… Commented Apr 6, 2020 at 13:55

2 Answers 2

2

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) 
Sign up to request clarification or add additional context in comments.

1 Comment

Which one is faster? it would be nice if they add such keyword to make it even nicer.
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

1 Comment

It is not about the str() method. That is just an example. How can I make that operation inside for loop?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.