Question about a Python for loop

  • Thread starter member 428835
  • Start date
  • Tags
    Loop Python
  • #1

member 428835

Hi All

I'm learning python and have never seen a for loop positioned like this:
Python:
integers = [4, 5, 7]
strings = [str(integer) for integer in integers]
I've only ever seen for loops positioned at the beginning of lines. Is this usual? How can I know when this is okay? I think I would have tried something like this instead
Python:
integers = [4, 5, 7]
strings = range(len(integers))
for i in integers:
    strings(i) = [str(i)]
 

Answers and Replies

  • #2
It's called a "list comprehension" and is a fairly common construct, yes.
 
  • Like
Likes member 428835
  • #3
It's called a "list comprehension" and is a fairly common construct, yes.
In Python... It's not a construct that's present in other, older languages, AFAIK. Possibly it's present in some of the newer languages.
 
  • Like
Likes Ibix, member 428835 and phinds
  • #5
I think I would have tried something like this instead
Your code has a syntax error in its last line. It also has two conceptual errors (three if you are using Python 3).

A really good piece of advice is to test any snippet of code in the interactive interpreter before posting it. Even better, post the actual interpreter session:

Python:
>>> integers = [4, 5, 7]
>>> strings = range(len(integers))
>>> for i in integers:
...     strings(i) = [str(i)]
...
  File "<stdin>", line 2
SyntaxError: cannot assign to function call
>>> for i in integers:
...     strings[i] = [str(i)]
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: 'range' object does not support item assignment
>>> strings = list(range(len(integers)))
>>> for i in integers:
...     strings[i] = [str(i)]
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
IndexError: list assignment index out of range
>>> for i in integers:
...     print(i)
...     strings[i] = [str(i)]
...
4
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
IndexError: list assignment index out of range
>>> for idx, i in enumerate(integers):
...     strings[idx] = [str(i)]
...
>>> strings
[['4'], ['5'], ['7']]
>>> for idx, i in enumerate(integers):
...     strings[idx] = str(i)
...
>>> strings
['4', '5', '7']
Only the very last is actually what is intended.
 
  • Like
Likes member 428835

Suggested for: Question about a Python for loop

Replies
1
Views
483
Replies
2
Views
135
Replies
3
Views
210
Replies
5
Views
705
Replies
10
Views
1K
Replies
6
Views
299
Back
Top