Reputation: 11
I'm trying to solve a project where i have to count the years in a list but I`m having problems understanding the difference between
years = [n[1] for n in data]
and
for n in data:
years = n[1]
here is the rest of the body
for m in years:
if m not in year_counts:
year_counts[m] = 0
year_counts[m] += 1
print(year_counts)
So if I use the first sentence then the code will run normally and will show the proper answer but if i use the second code it will give me random numbers I don't know from where.
Upvotes: 0
Views: 87
Reputation: 910
This code years = [n[1] for n in data]
output is list.
This code
for n in data:
years = n[1]
output is a single variable that contains last value.
Upvotes: 0
Reputation: 1
li = [1, 2, 3, 4, 5, 6, 7]
# For loop uses for list iteration.
# for loop iterate every item in a list.
for i in li:
print i
>>> 1
>>> 2
>>> 3
>>> 4
>>> 5
>>> 6
>>> 7
Upvotes: 0
Reputation: 385
In
for n in data:
years = n[1]
years
will be replaced for each n1. The "random" entry you are seeing is probably the second letter of the last entry in data.
You could do this instead to match the comprehension:
years = list()
data = ['a1', 'a2', 'a3', 'a4']
for n in data:
years.append(n[1]) # years = ['1', '2', '3', '4']
but
years = [n[1] for n in data]
will tend to be faster overall.
For your overall script, you might consider a using map.
Upvotes: 0
Reputation: 17803
years = [n[1] for n in data]
- years is now a list, each element is index [1] of an element in data
for n in data:
years = n[1]
years is a single object and is always updated with n[1] and will finally be index [1] of the last element in data
Upvotes: 1