Reputation: 23
I was trying to do a basic spinning animation using "\|/-" which went fine, but I wanted two on the same updating line. With one spinning clockwise and one spinning anti-clockwise.
Here is what I came up with:
animation_1 = ['\\', '|', '/', '-']
animation_2 = ['/', '|', '\\', '-']
while True:
for iteration_1, iteration_2 in animation_1, animation_2:
print(f'\r {iteration_2} {iteration_1}', end='')
sleep(.5)
sys.stdout.flush()
Which get the output:
"Traceback (most recent call last):
File "/Users/pungkrock/PycharmProjects/ans/fib.py", line 18, in <module>
for iteration_1, iteration_2 in animation_1, animation_2:
ValueError: too many values to unpack (expected 2)"
This example:
animation_1 = ['\\', '|', '/', '-']
animation_2 = ['/', '|', '\\', '-']
while True:
for iteration_1, iteration_2 in animation_1:
print(f'\r {iteration_2} {iteration_1}', end='')
sleep(.5)
sys.stdout.flush()
Gets the output:
"Traceback (most recent call last):
File "/Users/pungkrock/PycharmProjects/ans/fib.py", line 18, in <module>
for iteration_1, iteration_2 in animation_1:
ValueError: not enough values to unpack (expected 2, got 1)"
And this error massage I do understand. But I don't understand why I get an error message from the first example.
This example works fine:
animation_1 = ['\\', '|', '/', '-']
# animation_2 = ['/', '|', '\\', '-']
while True:
for iteration_1 in animation_1:
print(f'\r {iteration_1}', end='')
sleep(.5)
sys.stdout.flush()
Can some kind soul explain to me way the first code example doesn't work? Or if I'm missing some basic understanding of some concept of the language? "too many values to unpack (expected 2)", it did get 2? What am I missing?
Upvotes: 2
Views: 48
Reputation: 51034
I don't understand why I get an error message from the first example.
OK, let's walk through it. The relevant parts are that you have two lists of length 4, and then you tried to iterate over both of them with something like this:
a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
for i, j in a, b:
...
I'll use this code as an example because it's a bit simpler. There are two key points:
a, b
creates a tuple containing the two lists. It's the same as if you wrote (a, b)
.for i, j in something
only works if each element of something
is a sequence of length 2.From there, it's quite straightforward: the elements of the tuple (a, b)
are simply a
and b
themselves, which are sequences of length 4, not sequences of length 2. So, that's why there are too many values to unpack: 4 is too many.
Upvotes: 1
Reputation: 191711
in animation_1, animation_2
is not valid syntax
I assume you want to zip them
for a1, a2 in zip(animation_1, animation_2)
Upvotes: 0
Reputation: 14899
>>> for x in range(4):
... print(animation_1[x],animation_1[3-x])
...
\ -
| /
/ |
- \
sorry, no explanation, i am new to python meself too.... 😁
Upvotes: 0