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

Python

6376 readers
21 users here now

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

πŸ“… Events

PastNovember 2023

October 2023

July 2023

August 2023

September 2023

🐍 Python project:
πŸ’“ Python Community:
✨ Python Ecosystem:
🌌 Fediverse
Communities
Projects
Feeds

founded 1 year ago
MODERATORS
 

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
[–] bitfucker 2 points 4 months ago (8 children)

List comprehension is not whatever you're doing there. An example of list comprehension:

list = [value*2 for value in range(1, 20)]

See, list comprehension is used to make a list from an existing list. The value of the new list is defined by a function. In this case, the value of a will be 2,4,6, etc.

Your current syntax list[...], is trying to access an element of a list.

[–] [email protected] 1 points 4 months ago (7 children)

So you cannot use methods inside a list comprehension, only binary operators and the function range?

[–] bitfucker 2 points 4 months ago* (last edited 4 months ago) (5 children)

You can. Whatever the method returns will be the element of that list. So if for example I do this:

def mul(x):
  return x*2

list = [mul(value) for value in range(1,20)]

It will have the same effect. But this:

def mul(x):
  return

list = [mul(value) for value in range(1,20)]

Will just makes the list element all None

Edit to add more: List comprehension works not from the range function. Rather, the range function is returning a list. Hence the name, "list comprehension". You can use any old list for it.

What it did under the hood is that it iterates each element on the list that you specify (the in ...), and applies those to the function that you specify in the very first place. If you are familiar with the concept of Array.map in other languages, this is that. There is also a technical explanation for it if it helps, but it requires more time to explain. Just let me know if you would like to know it.

[–] [email protected] 1 points 4 months ago* (last edited 4 months ago) (1 children)

I know I'm being somewhat pedantic but range() returns an iterable range type, not a list, in python 3.

[–] bitfucker 1 points 4 months ago

Not at all. It is indeed helpful to differentiate between an iterable and literal list. After all, sometimes it will bite you in the ass when you don't differentiate between the two.

load more comments (3 replies)
load more comments (4 replies)
load more comments (4 replies)