Python Forum
Python List Comprehension.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python List Comprehension.
#1
Can you please explain me Python List Comprehension.
Reply
#2
Did you check our tutorial on comprehension expressions? Or any other available online? It will be easier to help if you are more specific which part you don't understand.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
The list comprehension is a way to declare a list in one line of code. Let’s take a look at one such example.

>>> [i for i in range(1,11,2)]
[1, 3, 5, 7, 9]

>>> [i*2 for i in range(1,11,2)]
[2, 6, 10, 14, 18]
Reply
#4
As almost everything else in Python it's very close to natural language. This Python code:

>>> [x for x in range(10) if x % 2 == 0]
[0, 2, 4, 6, 8]
translates into English: give me an x for every x in range 0-9 if x is even
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  List comprehension: paul18fr 1 1,378 Oct-29-2021, 05:36 PM
Last Post: Yoriz
  list comprehension invalid syntax mcgrim 1 4,696 Jun-12-2019, 08:28 PM
Last Post: Yoriz
  Help me understand a simple list comprehension PiPy 6 3,948 Oct-17-2018, 07:59 PM
Last Post: PiPy

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020