Reputation: 37
I have a basic Python encryption program. The program is pretty much done, but I keep getting errors because of the way Python is building my variable.
Here is an example of what I am trying to do:
A = 4
B = 2
C = 3
for i in range (3):
A=A, ((B*2) + C)
A = (((4, 7), 7), 7)
I want A to output 4, 7, 7, 7 and as it loops, it adds numbers onto the end instead of adding them together. The issue here is that for whatever reason, I can't target specific values, for example, if I did
print (A[2])
The output would be an error
Traceback (most recent call last):
File "C:/Users/name/Desktop/Python/Test.py", line 8, in <module>
print (A[2])
IndexError: tuple index out of range
Ignoring the above code, what is the best way I could do this? Thanks!
Upvotes: 1
Views: 965
Reputation: 593
If you want to keep using a tuple you can do it like this:
A = 4
B = 2
C = 3
A = (A,) # Convert A to tuple
for i in range(3):
A += ((B*2) + C,)
print(A)
# (4, 7, 7, 7)
Note: tuples are immutable, which means you are creating a new tuple in each iteration, this can be an expensive operation if the loop is very big.
Upvotes: 0
Reputation: 18047
Did you mean this,
A = 4
B = 2
C = 3
l = [A]
for i in range (3):
l.extend([B*2 + C])
print(l)
# [4, 7, 7, 7]
Upvotes: 1