0

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

3

2 Answers 2

1

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

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

1 Comment

Yeah this works too although my only comment on this approach is that it is better to use a named list than use a tuple for maintainability,
1

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])

3 Comments

Tkz alot got😊 it helped me
How to do tht i m new here
Oh on the left side of the answer below the score you'll see a check mark. Click on it to mark as accepted.

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.