Santosh Kumar
Santosh Kumar

Reputation: 11

List Comprehension, For-Loop give differing results

from sklearn.datasets import load_iris
data = load_iris()
iris = pd.DataFrame(data.data,columns = data.feature_names)
  1. iris['target_names'] = [data.target_names[i] for i in data.target]

  2. for i in data.target: iris['target_names'][i] = data.target_names[i]

Why is the first bit of code is giving a different result in comparison to second?

Upvotes: 0

Views: 69

Answers (1)

Stephen Rauch
Stephen Rauch

Reputation: 49794

The first line:

iris['target_names'] = [data.target_names[i] for i in data.target]

generates a list of of the elements data.target_names[i]

The second bit:

for i in data.target:
    iris['target_names'][i]  = data.target_names[i]

references all of the same pieces, but stores them into:

iris['target_names'][i]

The only way this would generate the same thing as the comprehension is if iris['target_names'] were a list of the same length data.target and data.target contained the equivalent of range(len(data.target)).

Equivalent Comprehension

To build a comprehension that is the same as the loop (in 2), iris['target_names'] likely needs to be a dict.

iris['target_names'] = {i: data.target_names[i] for i in data.target}

same as:

for i in data.target: 
    iris['target_names'][i] = data.target_names[i]

Equivalent Loop

To build a loop that is the same as the comprehension (in 1), you will need to append to a list like:

iris['target_names'] = []
for i in data.target:
    iris['target_names'].append(data.target_names[i])

Same as:

iris['target_names'] = [data.target_names[i] for i in data.target]

Upvotes: 0

Related Questions