A Simple Introduction to List Comprehension in Python

preview_player
Показать описание
List comprehension is a compact way of creating lists. The simple formula is [ expression + context ].

- Expression: What to do with each list element?
- Context: What list elements to select? It consists of an arbitrary number of for and if statements.

The example [x for x in range(3)] creates the list [0, 1, 2].

In this article, you will learn everything you need to know about list comprehension in Python. Being hated by newbies, experienced Python coders can’t live without this awesome Python feature.

Read the full article at:

~~~
Become a better coder! Download the 5x Python Cheat Sheet Course (PDF). It’s free!

🐍 Cheating in Python? Of course! 🐍
See you soon -- it’s fun! 🤓
~~~

Experts in their fields read more books! Become a Python expert:

And become a Python master the fun way!
~~~

Start earning money by creating your own Python coding business (free webinar):
Рекомендации по теме
Комментарии
Автор

Excellent! Thank you, I have spent 3 days looking for a simple, understandable explanation and this is it.

barriesimpson
Автор

Here's my code:

import time as t

def f1(n):
return ''.join([str(x) for x in range(n)])

def f2(n):
s = ''
for x in range(n):
s += str(x)
return s

n = 10**6
t1 = t.time()
f1(n)
t2 = t.time()
f2(n)
t3 = t.time()

print(t3 - t2 > t2 - t1)

The solution is True, but I got False. I researched and found that there are various reasons for this. However, I am not sure where to start on finding out exactly why and if this will affect future String puzzles.

evelynnmimijae
visit shbcf.ru