Python \ n index

Ok, here I have another problem, I only need to find the position \n in my list.

 list = ['abc', '\n', 'def', 'ghi', '\n', 'jkl'] 

So, I need to get the position of all the entries "\ n" from this list.

I used

 a=list.index('\n') 

but received only one value as '1'. How to get both positions?

eg. I will get a list with position '\ n'

position = ['1', '4']

'1' represents the first position of the list \ n in the list, and '4' represents the second in fourth place in the list.

+4
source share
3 answers

You will need to iterate over the elements. This can be easily done using list comprehension and enumerate for indexes:

 indexes = [i for i, val in enumerate(list) if val == '\n'] 

Demo:

 >>> lst = ['abc', '\n', 'def', 'ghi', '\n', 'jkl'] >>> [i for i, val in enumerate(lst) if val == '\n'] [1, 4] 
+11
source
 [i for i, x in enumerate(l) if x == "\n"] # => [1, 4] 

And do not call the list , as this is a built-in function.

+4
source

To find the indices of an item in a multiple-entry list, the following code should work

 print [i for i in range(len(list)) if list[i] == '\n'] 

Here I used list , as was customary in your question, but does not use keywords as variables.

0
source

All Articles