Practice makes perfect


#1



to_21=range(1,22)
odds=[to_21 for to_21 in range(1,22) if(to_21)%2!=0]
print odds
middle_third = to_21[8:15:1]
print middle_third

Traceback (most recent call last):
  File "python", line 4, in <module>
TypeError: 'int' object has no attribute '__getitem__'
 
what is wrong in this


#2

lets see what to_21 is:

to_21=range(1,22)
odds=[to_21 for to_21 in range(1,22) if(to_21)%2!=0]
print odds
print to_21
middle_third = to_21[8:15:1]
print middle_third

is a integer, that explains a lot.

Because you use it as loop value/iterator in the list comprehension, it will contain the last integer value from the list (overwriting the list which was stored in this variable)

I would make some changes to your list comprehension to prevent overwriting to_21 list


#3

same error is coming


#4

Did you make the changes i suggested? The code i posted above only is to show the problem


#5

to_21=[i for i in range(1,22)]
odds=[to_21 for to_21 in range(1,22) if(to_21)%2!=0]
print odds
print to_21
middle_third = to_21[7:14:1]
print middle_third

i did this


#6

see this line i added:

print to_21

it shows you to_21 is no longer a list, but rather a integer. It should be a list, but given you also used it as loop iterator, it no longer is, make the changes to your list comprehension.


#7

tnx bro...........!!


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.