19
submitted 2 months ago* (last edited 2 months ago) by librejoe@lemmy.world to c/python@programming.dev

I'm new to programming a bit, and am learning python so I can learn flask, using the python crash course book. I was learning about list comprehension but it briefly talks about it. If I do

list[list.append(value) for value in range(1, 20)]

it doesn't work. Would this be some sort of recursive expression that is not possible?

you are viewing a single comment's thread
view the rest of the comments
[-] decivex@yiffit.net 5 points 2 months ago* (last edited 2 months ago)
  1. list.append returns None so what you've actually got is a list comprehension that generates a list containing the value None 19 times. (using functions with side effects, such as list.append, in list comprehensions are generally bad style so you should avoid this)
  2. The list[...] syntax retrieves elements from the list, which is not what you're trying to do here. (and it is actually invalid syntax in this case)
  3. You should generally avoid calling lists list, because list is already a builtin.

If you want to append the numbers 1 to 19 to a list as you're trying to do you can call the list.extend function with the list comprehension [value for value in range(1, 20)] as the argument. (Although in this case you can also just use the range directly.) To do it without list comprehensions you can simply loop over the range and repeatedly call the append function.

this post was submitted on 25 Jun 2024
19 points (95.2% liked)

Python

6219 readers
22 users here now

Welcome to the Python community on the programming.dev Lemmy instance!

📅 Events

October 2023

November 2023

PastJuly 2023

August 2023

September 2023

🐍 Python project:
💓 Python Community:
✨ Python Ecosystem:
🌌 Fediverse
Communities
Projects
Feeds

founded 1 year ago
MODERATORS