Reputation: 3
I have a list l1 =[1,56,67,79,90,47,08,56,79,84,76,79,68,]
Now, I want to print indices 4,6,9,10 alone using a loop
I tried:
for i in l1:
Print(i[4]..)
But it says: int is not subscriptable
Upvotes: 0
Views: 2204
Reputation: 8097
if you just want to loop over all items in the list by the indexes you could do something like this:
l1 =[1,56,67,79,90,47,8,56,79,84,76,79,68]
for i in range(len(l1)):
if i in (4, 6, 9, 10):
print(l1[i])
that being said, this is not the most efficient thing
Upvotes: 1
Reputation: 468
I am assuming this is for a homework and so you want to use loops for this.
When you say i in l1
each element i
is an int
and so it won't work to index it.
If you are trying to specifically print elements in indexes 4, 6, 9, 10 then you need to put these in a list and iterate over these. So for ex:
l1 =[1,56,67,79,90,47,08,56,79,84,76,79,68,]
to_print = [4, 6, 9, 10] # So if you want to print other/more index positions then modify this. Note that you may want to do a length check too before using these indexes as is.
for i in to_print:
print(l1[i])
Upvotes: 1