I want my output like if I choose the element 5 (not the index), only 4,7,6
will be printed.
b = [1,3,2,5,4,7,6]
Node = 5
for i in b:
if Node == b[i-1]:
continue;
print(b[i-1])
CodePudding user response:
You could use the index
method and then use the found index to slice the list:
b = [1,3,2,5,4,7,6]
Node = 5
index = b.index(Node)
for i in b[index 1:]:
print(i)
CodePudding user response:
def main():
b = [1, 3, 2, 5, 4, 7, 6]
node = 5
for i in range(-1, -len(b), -1):
if b[i] == node:
for j in b[i 1:]:
print(j)
return 0
for i in b:
print(i)
if __name__ == "__main__":
main()
CodePudding user response:
b = [1, 3, 2, 5, 4, 7, 6]
Node = 5
print(b[b.index(Node) 1::]) # [4, 7, 6]
CodePudding user response:
b = [1,3,2,5,4,7,6]
Node=5
index=b.index(Node)# fetching index of node
for i in b[index 1::]: #iterating through list after the node
print(i)
CodePudding user response:
To avoid slicing and creating new lists, you can create an iterator over the list and consume it until you reach the element, then print what is left:
l = [1, 3, 2, 5, 4, 7, 6]
node = 5
it = iter(l)
for num in it:
if num == node:
break
for num in it:
print(num)
Or use itertools.dropwhile
to avoid the first loop:
import itertools
l = [1, 3, 2, 5, 4, 7, 6]
node = 5
it = itertools.dropwhile(lambda x: x != node, l)
next(it)
for num in it:
print(num)