Hi, how are you?
I am a student who just started studying Python.
What I was going to do was take the words and process them.
In the meantime, the following phenomenon happened by chance.
I'm asking you a question because I don't understand.
wl = []; nl = []
[wl.append(input()) for t in range(int(input()))]
[wl.append('hello') for t in wl]
First, you get the number of words you get and you get the word one line at a time.
3
hello
hash
code
Like this.
And I'm trying to add 'hello' to the end of this list of words, but all of a sudden, I keep getting input.
3
hello
hash
code
Input is
Continue
It's working.
[Correction]
[wl.append('hello') for t in range(len(wl))]
The last line is changed like that, so it works properly. But I don't know the difference and the obvious reason.
[Correction]
I added a screenshot;
The questioner is misunderstanding.
It doesn't repeat itself indefinitely.[wl.append('hello') for t in wl] The cursor is blinking for the time it takes for the code to run...The questioner thinks the input keeps coming in.
Run the program and look at the memory state. It's going to keep increasing.In a few minutes, the process will end with a memory error.
(py36) allinux@~$ python -V
Python 3.6.2
(py36) allinux@~$ cat abcd.py
wl = []; nl = []
[wl.append(input()) for t in range(int(input()))]
#[wl.append('hello') for t in wl]
(py36) allinux@~$ python abcd.py
3
aaa
bbb
ccc
(py36) allinux@~$
Please correct the test as below and try it.
wl = []; nl = []
[wl.append(input('Input a string: ')) for t in range(int(input('Input a Number: ')))]
[wl.append('hello') for t in wl]
[wl.append('hello') for t in wl]
For t in wl is to get elements from wl one by one by one. That is, if there are 3 elements, you will look up 3 elements. However, every iteration calls the wl.append again to add elements to the wl, which is eventually an infinite iteration.
[wl.append('hello') for t in range(len(wl))]
Gets the list size of the time point when called by len(wl). len(w) is not affected by wl.append because it is called only once.
© 2024 OneMinuteCode. All rights reserved.