Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find index of an element in Python list? [duplicate]

Possible Duplicate:
How to find positions of the list maximum?

A question from homework: Define a function censor(words,nasty) that takes a list of words, and replaces all the words appearing in nasty with the word CENSORED, and returns the censored list of words.

>>> censor([’it’,’is’,’raining’], [’raining’])
[’it’,’is’,’CENSORED’]

I see solution like this:

  1. find an index of nasty
  2. replace words matching that index with "CENSORED"

but i get stuck on finding the index..

like image 557
Gusto Avatar asked Nov 04 '10 13:11

Gusto


People also ask

How do I find the index of a duplicate element in a list?

Using enumerate with for-loop and if statement you can get the index of duplicate elements in python list.

How do you find the index value of a element in a list Python?

To find the index of an element in a list, you use the index() function. It returns 3 as expected.

Can pandas duplicate indexes?

Indicate duplicate index values. Duplicated values are indicated as True values in the resulting array. Either all duplicates, all except the first, or all except the last occurrence of duplicates can be indicated. The value or values in a set of duplicates to mark as missing.


2 Answers

You can find the index of any element of a list by using the .index method.

>>> l=['a','b','c']
>>> l.index('b')
1
like image 181
MAK Avatar answered Oct 14 '22 06:10

MAK


Actually you don't have to operate with indexes here. Just iterate over words list and check if the word is listed in nasty. If it is append 'CENSORED' to the result list, else append the word itself.

Or you can involve list comprehension and conditional expression to get more elegant version:

like image 45
z4y4ts Avatar answered Oct 14 '22 08:10

z4y4ts