Python Forum

Full Version: help for use print in REPL
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Hi
I try to test this basic code in REPL

a = [1, 2, 3, 4, 5]
for x in range(len(a)):
    print a[x]
I don't succeed to display the list result : 1, 2,3
After for x in range(len(a)): there is an identation
So I am doing tab + print(a) but there is an stdin error
what is wrong please?
Hi,

Perhaps you mean
print(x).
or
for x in a:
print(x)

Paul
(Apr-29-2021, 09:18 AM)DPaul Wrote: [ -> ]Hi,

Perhaps you mean
print(x).
or
for x in a:
print(x)

Paul

Hi
No
Like explained, I need to display the list and the name list is a
No, no and no. Never write such a code. This ain’t Java, this is Python:

for item in iterable:
    print(item)
And if you are using Python2 then support of it has ended quite some time ago. Consider upgrading.
Hi Jip31,
Although it is right what Perfringo said, for the purpose of studying: what your code gives me is the following:
Error:
File "forum03.py", line 3 print a[x] ^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print(a[x])?
print a[x] is old Python 2 syntax. In Python 3 "print()" is a function. When you correct this:
a = [1, 2, 3, 4, 5]
for x in range(len(a)):
    print(a[x])
... the result is:
Output:
1 2 3 4 5
(Apr-29-2021, 10:45 AM)ibreeden Wrote: [ -> ]Hi Jip31,
Although it is right what Perfringo said, for the purpose of studying: what your code gives me is the following:
Error:
File "forum03.py", line 3 print a[x] ^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print(a[x])?
print a[x] is old Python 2 syntax. In Python 3 "print()" is a function. When you correct this:
a = [1, 2, 3, 4, 5]
for x in range(len(a)):
    print(a[x])
... the result is:
Output:
1 2 3 4 5


thanks ibredeen (sorry I have one week python background....)
And a tip - whenever you have range(len(... there is a better way.
In this case
a = [1, 2, 3, 4, 5]
for x in a:
    print(x)
Reiterating Perfringo, but specifically this case. For x in a pulls the elements of the list a. You then print (using Python 3 syntax for the print statement)

You may also want to look at list comprehensions. Not the best example, but
a = [1,2,3,4,5]
[print(x) for x in a]
Gets it down to 2 lines
I think it is poor practice using a comprehension or any code for its side effects. My linter agrees.
No, no and no. Never write such a code. This ain’t Java, this is Python
Really, people should be learning how to program more declaratively anyway (a good talk on this: https://youtu.be/nrVIlhtoE3Y). To be fair to Java, that's done by making use of the Streams API
Pages: 1 2