I have a question regarding the Python list indexing.

Asked 1 years ago, Updated 1 years ago, 78 views

stack = [3, 4, 5, 8, 0]
print('stack : [')
for x in stack:
    print(stack[x], end='')
    if x >= 4:
        print(']')
        break;

As above, I tried to check if the value is output after declaring and assigning a list variable called stack. However, I don't understand why it's like this when you actually run it and only stack = [80].

I thought x would start with the zero subscript and then stack[0] = 3 and print it out, but the result is different from what I thought.

What do I misunderstand?

python list indexing

2022-09-21 18:25

1 Answers

When for x in stack:, x contains the values in the stack one by one.

So, I have to print(x) instead of print(stack[x]). Did you happen to want this to happen?

stack = [3, 4, 5, 8, 0]
print('stack : [')
for x in stack:
    print(x)
print(']')


2022-09-21 18:25

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.