Home > Enterprise >  Jump Print in Python
Jump Print in Python

Time:10-22

i dont know what the name of this call method, this my simple python code

fruits1 = ["banana","avocado","grape","orange","strawberry"]
for a in fruits1:
 print(a)

if normal the print(a) output like this

banana
avocado
grape
orange
strawberry

so how to make output result print (a) like this

avocado
grape
orange
strawberry

i want to jump and first result in avocado

thanks

CodePudding user response:

Try this :

for a in fruits1[1:]:
 print(a)

CodePudding user response:

Try this:

fruits1 = ["banana","avocado","grape","orange","strawberry"]
for a in fruits1[1:]:
    print(a)

CodePudding user response:

You basically want to consider your list items minus the first items. Either you can loop through the list starting from 2nd element. Or you can directly print the list using sep='\n',

print(fruits1[1:], sep='\n')

Or simple loop through the list and print each item one by one,

for a in fruits1[1:]:
 print(a)

The key here is Slicing your list from the first position. Alternatively you can delete the first item and print the list, depending on your requirement.

CodePudding user response:

You can try following

fruits = ["banana","avocado","grape","orange","strawberry"]
for a in fruits[1:]:
    print(a)

or you can have separate list for keeping items not to print

fruits = ["banana","avocado","grape","orange","strawberry"]
exclude = ["banana"]
for a in fruits:
    if a not in exclude:
        print(a)

CodePudding user response:

If you need to just skip the first element, the answers already provided will suffice. If you need to print all elements starting wherever in the list a particular item occurs, then you need to modify the answers also provided.

We'll wrap this up in a function and incorporate some exception handling in case we try to look for something not in the list. Instead of hard-coding 1 as an index, we'll look for the first index in the list where a provided value occurs and use that to get a list slice.

def list_slice_from_value_to_end(lst, val):
    try:
        return lst[lst.index(val):]
    except ValueError:
        return []

Now we can write a loop like the following:

for a in list_slice_from_value_to_end(fruits, "avocado"):
    print(a)
  • Related