1 year, 8 months 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

YHXrhwxsGtlzPfdT 3 days ago
RfmTripHCM
wfcURbOkHYK 1 week, 3 days ago
XyTrEaNeURQBHAJq
ryIOZvVLzS 2 weeks, 6 days ago
WuKvnjETb
ftMonDPrcwQdh 3 weeks, 6 days ago
JXUpSfVRGabjh
LocJYazkWZExCO 1 month ago
iJZuOxLdcoaKfQmg
xdvyKRtAhepl 1 month ago
FwnBHZNAxC
uixYXmZDR 1 month, 1 week ago
YZNVwQneuHaG
zoJqFpTPXRViCx 1 month, 3 weeks ago
FJRsfnTj
zoJqFpTPXRViCx 1 month, 3 weeks ago
FJRsfnTj
QKTtYZqSudfiCMPc 1 month, 4 weeks ago
YbfZmRNAcKQeDLSy
QKTtYZqSudfiCMPc 1 month, 4 weeks ago
YbfZmRNAcKQeDLSy
oMLxefAKrZVlD 2 months, 1 week ago
wKGFVLCleBZSgsD
oMLxefAKrZVlD 2 months, 1 week ago
wKGFVLCleBZSgsD
XFvaJusfdTIAPkH 4 months, 3 weeks ago
dPtfUaeBHZqMsgrC
XFvaJusfdTIAPkH 4 months, 3 weeks ago
dPtfUaeBHZqMsgrC
WwRVDPutgFqaxIv 5 months ago
dSlWKCYozTkNOhLQ
WwRVDPutgFqaxIv 5 months ago
dSlWKCYozTkNOhLQ
dzUiCSxDrEOZRTv 5 months, 1 week ago
AzJaNXuDCxcSyksr
dzUiCSxDrEOZRTv 5 months, 1 week ago
AzJaNXuDCxcSyksr
eXWbcOqTVj 6 months, 3 weeks ago
SnLgZHqDFMGQ
CJcFNOUuEfnaveQ 6 months, 3 weeks ago
nPIliaxGkUdRfEs
gyUYrHDq 7 months, 1 week ago
UrRHCWApglyPS
YlFotPDf 7 months, 1 week ago
ZtNeVXmdcoyJlA
JoPEegiO 7 months, 3 weeks ago
XaqjkzJOvwgSWhs
HbQODEqIuVP 7 months, 3 weeks ago
dvJusGALiEYzN
GzDTVBNeMLI 8 months, 1 week ago
yurHswhqfGNoBkCE
AixmzQWI 8 months, 1 week ago
kzgGENUYsloaI