-2

I need to assign a result of for loop to a variable. It is easy to print the for loop in a single line using end =" ", but I am unable to assign the result as a single line.

a = [1, 2, 3, 4]

for i in range(4):
    print(a[i], end =" ")

Result is 1 2 3 4

But I have to assign the result to a variable as var = 1234.

I am trying below way which is incorrect and not providing the result:

a = [1, 2, 3, 4]

for i in range(4):
    var = print(a[i], end =" ")
    print(var) # It provides the result in multiple line

What can I try next?

halfer
  • 19,824
  • 17
  • 99
  • 186
Jim Macaulay
  • 4,709
  • 4
  • 28
  • 53
  • 1
    in this case is `var` an integer? – cards Mar 05 '23 at 14:33
  • 1
    `print` always returns `None` so assigning the result of `print` to `var` is one problem. – GIZ Mar 05 '23 at 14:34
  • @GIZ maybe smt like this `var = [a[i], print(a[i], end=' ')][0]` – cards Mar 05 '23 at 14:36
  • @cards Syntax error aside, I'm not sure what you think that is supposed to accomplish. `print` does not produce usable data; it only returns `None` after writing to a file. – chepner Mar 05 '23 at 14:38
  • Do you want the integer `1234` or the string `'1234'` as the result? – chepner Mar 05 '23 at 14:39
  • @chepner the code works without syntax error – cards Mar 05 '23 at 14:41
  • @cards You changed it since I made that comment. But the call to `print` has no effect on your assignment to `var`. You create the list `[a[i], None]`, then just assign `a[i]` to `var`. – chepner Mar 05 '23 at 14:44
  • 1
    I am downvoting because this question lacks clarity. The _question_ is about assigning variables in a for loop, but the the _answer_ the OP seems to be seeking is more about how to print a list of ints as a single concatenated value. It's also a somewhat common problem that has been answered many times (if you ask the right question - how to concatenate a list of ints). For example: [how-to-concatenate-join-items-in-a-list-to-a-single-string](https://stackoverflow.com/questions/12453580/how-to-concatenate-join-items-in-a-list-to-a-single-string) – topsail Mar 05 '23 at 18:24

3 Answers3

0

Use join to achieve this when a is a list of numbers

a = [1, 2, 3, 4]
var = ''.join(str(num) for num in a)
A-T
  • 342
  • 2
  • 14
0

You can use the join() method to concatenate the elements of the list as a string and then assign the string to the variable.

For Example :

a = [1, 2, 3, 4]
var = ''.join(str(i) for i in a)
print(var) # Output: '1234'

Other way to do this is :

a = [1, 2, 3, 4]
var = ''.join(map(str, a))
print(var) # Output: '1234'
Jagroop
  • 1,777
  • 1
  • 6
  • 20
0

You can use a list comprehension along with the join() function to achieve this:

a = [1, 2, 3, 4]
var = ''.join([str(i) for i in a])
print(var)  # Output: 1234
Michał Zaborowski
  • 3,911
  • 2
  • 19
  • 39
qubitbrain
  • 19
  • 2