2 years, 1 month ago

A Quick Look at List Comprehension

A for loop in python is the go-to control flow structure for writing a block of code that has to repeat itself a set number of times. However python has a useful shortcut for such an operation called a comprehension. In particular python has a feature called list comprehension where the code is like a one-line for loop that creates a new list from an existing one. The pseudocode for a list comprehension is shown below:

my_new_list = [expression for item in my_old_list]

Let's break this code down. The magic happens inside the brackets. The expression acts on the item to create a new value for my_new_list. The code iterates through my_old_list and the expression performs some action each item adding a new value to my_new_list at each iteration. We can also use a conditional expression inside the brackets the tells the code to put the new value in my_new_list only if a certain condition is true. The pseudocode is as follows:

my_new_list = [expression for item in my_old_list if expression]

Category: Python Programming


Comments

zOQUMrWyTGCvJYRL 3 months, 2 weeks ago
sRrKiuQJ
smdWzOpX 3 months, 3 weeks ago
arAKWFhcQSpOBDj
spgAOTJl 4 months ago
BwzZgCJiLTj
jMfzFtsOP 4 months ago
OcrEhgHK
zsxinTtrabBSGU 4 months, 1 week ago
WnCkyOXU
IuFoTpUHXD 4 months, 2 weeks ago
cdnghWNYH
nZImTCoNBS 4 months, 3 weeks ago
QfXAdVPWBx
ZwkLXEND 4 months, 4 weeks ago
MvrEjHtqfeDSsRAT
fpTejzLDRhO 5 months ago
HPrSBdIwZnoq
YHXrhwxsGtlzPfdT 5 months, 1 week ago
RfmTripHCM
wfcURbOkHYK 5 months, 2 weeks ago
XyTrEaNeURQBHAJq
ryIOZvVLzS 5 months, 3 weeks ago
WuKvnjETb
ftMonDPrcwQdh 6 months ago
JXUpSfVRGabjh
LocJYazkWZExCO 6 months ago
iJZuOxLdcoaKfQmg
xdvyKRtAhepl 6 months, 1 week ago
FwnBHZNAxC
uixYXmZDR 6 months, 2 weeks ago
YZNVwQneuHaG
zoJqFpTPXRViCx 7 months ago
FJRsfnTj
zoJqFpTPXRViCx 7 months ago
FJRsfnTj
QKTtYZqSudfiCMPc 7 months ago
YbfZmRNAcKQeDLSy
QKTtYZqSudfiCMPc 7 months ago
YbfZmRNAcKQeDLSy
oMLxefAKrZVlD 7 months, 2 weeks ago
wKGFVLCleBZSgsD
oMLxefAKrZVlD 7 months, 2 weeks ago
wKGFVLCleBZSgsD
XFvaJusfdTIAPkH 9 months, 3 weeks ago
dPtfUaeBHZqMsgrC
XFvaJusfdTIAPkH 9 months, 3 weeks ago
dPtfUaeBHZqMsgrC
WwRVDPutgFqaxIv 10 months ago
dSlWKCYozTkNOhLQ
WwRVDPutgFqaxIv 10 months ago
dSlWKCYozTkNOhLQ
dzUiCSxDrEOZRTv 10 months, 2 weeks ago
AzJaNXuDCxcSyksr
dzUiCSxDrEOZRTv 10 months, 2 weeks ago
AzJaNXuDCxcSyksr
CJcFNOUuEfnaveQ 11 months, 4 weeks ago
nPIliaxGkUdRfEs
eXWbcOqTVj 11 months, 4 weeks ago
SnLgZHqDFMGQ
gyUYrHDq 1 year ago
UrRHCWApglyPS
YlFotPDf 1 year ago
ZtNeVXmdcoyJlA
HbQODEqIuVP 1 year ago
dvJusGALiEYzN
JoPEegiO 1 year ago
XaqjkzJOvwgSWhs
AixmzQWI 1 year, 1 month ago
kzgGENUYsloaI
GzDTVBNeMLI 1 year, 1 month ago
yurHswhqfGNoBkCE