List comprehension
List comprehensions are a concise and convenient way to address a common programming task:
iterating through a list, making a calculation, and saving the calculation into a new list.
While this can be performed using a for
loop, a list comprehension preforms the same task with fewer number of lines.
The following list comprehension squares all values in a list:
x = [1, 2, 3, 4]
print([i**2 for i in x])
[1, 4, 9, 16]
A list of file names has been provided to you in the inflam_files
list. Your task is to write a list comprehension that imports these files as pandas DataFrames in a single list.
This exercise is part of the course
Python for R Users
Exercise instructions
- Re-write the provided for loop as a list comprehension:
dfs_comp
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Append dataframes into list with for loop
dfs_list = []
for f in inflam_files:
dat = pd.read_csv(f)
dfs_list.append(dat)
# Re-write the provided for loop as a list comprehension: dfs_comp
dfs_comp = [____.____(____) for ____ in ____]
print(dfs_comp)