How to prevent tuples inside tuples?

Question:

I am trying to do what is shown in the following code

repeat = 0
x = "1"

while repeat != 3:
    x = x, x
    repeat = repeat + 1

print(x)

However, it outputs:
(((‘1’, ‘1’), (‘1’, ‘1’)), ((‘1’, ‘1’), (‘1’, ‘1’)))

How can I make it so it outputs:
‘1’, ‘1’, ‘1’, ‘1’, ‘1’, ‘1’, ‘1’, ‘1’

I don’t want this exact output this is just an example. Is this possible?

Asked By: Kian Murray

||

Answers:

I tried solving your question like this. I hope it fixes your problem.

repeat = 0
x = "1"

while repeat != 3:
    x = x + "," + x 
    repeat += 1

print(x)

Basically, concatenating the strings.

Alternative answer:

repeat = 0
x = ["1"]

while repeat != 3:
    x = x + x
    repeat = repeat + 1

print(x)

If you want a list of size n of just 1s

Here’s how I did it:

n = 3 
y = ["1"]
x = y*n
print(x)
Answered By: Inshaullah

More pythonic way is to use join to get the expected output.
If you want to repeat it N times –

N = 8
char = '1'

result = "','".join(char * N)

If you want to continue using loop, just concatenate the character instead of creating tuple every time you iterate.

Answered By: Faruk Ahmad
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.