Very new Python learner here - please be gentle. I'm having some problems picking up the concept of list comprehensions in Python so I'm trying to equate list comprehensions code in terms of for loops.
I was given a problem wherein I have 2 lists: One is a list of values and the second is a list of indices. The job was to use the list of indices to extract those columns from the list of values to create a shorter list. So for example if the lists are:
my_table = ['1', '2', '3', '4']
['5', '6', '7', '8']
['-2', '-3', '-4', '-5']
col_indices = [0, 2]
We want:
Output = ['1', '3']
['5', '7']
['-2', '-4']
So I have seen this post on Stack Overflow before and I know a way to do this with one list comprehension is as follows:
answer = []
for row in my_table:
reduced_row = [row[idx] for idx in col_indices]
answer.append(reduced_row)
return answer
To be honest I kind of get this but not completely. To better my understanding I tried to write some nested loops to get the same result but realized I don't have a good way to do this with my current level of comprehension.
Originally I tried the following:
col_list = []
for row in my_table:
for idx in col_indices:
new = [row[idx]]
col_list.append(new)
return col_list
But I know this is wrong because it just appends ever value to the first column. In short, I KNOW that list comprehension is the more efficient way to pull out columns from indices like this but this code was provided for me and I'm not sure I could have written it on my own with my current level of understanding. In an attempt to better parse the idea of list comprehension I'm trying to figure out a way this could be done only using loops but I have not yet figured out a way to do so. Can someone help me figure this out so hopefully I can get a better handle on how this code works?