0

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.

1
  • What does the data in years look like? Commented Dec 8, 2017 at 15:01

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Might be helpful to show data = ['1922', '1999', '2017'], and that years will either be ['9', '9', '0'] or '0'
0

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.

2 Comments

I see. so years = [n[1] for n in data] could be translated to years = [] for n in data: years.append(n[1])
Right. But loops are slower than list comprehensions in general.
0
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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.