Try:
for word in words:
if word[0] == word[-1]:
c += 1
print c
for word in words returns the items of words, not the index. If you need the index sometime, try using enumerate:
for idx, word in enumerate(words):
print idx, word
would output
0, 'aba'
1, 'xyz'
etc.
The -1 in word[-1] above is Python's way of saying "the last element". word[-2] would give you the second last element, and so on.
You can also use a generator to achieve this.
c = sum(1 for word in words if word[0] == word[-1])
Answer from Steinar Lima on Stack OverflowI'm trying to loop over a list of strings. So how can I continue with iterating the inner loop with the outer Index.
l1 = [str1, str2, str3,str4,str5,str6,str7,str8,str9]
temp = []
for str in l1:
If re.search(r'.*4',str) :
for str in l1: if str is str8: break else: temp.append(str)
Output : temp = [ str5,str6,str7]
The above code is the pseudo code. I want to append strings to temp, if they match particular pattern.
Try:
for word in words:
if word[0] == word[-1]:
c += 1
print c
for word in words returns the items of words, not the index. If you need the index sometime, try using enumerate:
for idx, word in enumerate(words):
print idx, word
would output
0, 'aba'
1, 'xyz'
etc.
The -1 in word[-1] above is Python's way of saying "the last element". word[-2] would give you the second last element, and so on.
You can also use a generator to achieve this.
c = sum(1 for word in words if word[0] == word[-1])
The suggestion that using range(len()) is the equivalent of using enumerate() is incorrect. They return the same results, but they are not the same.
Using enumerate() actually gives you key/value pairs. Using range(len()) does not.
Let's check range(len()) first (working from the example from the original poster):
words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
print range(len(words))
This gives us a simple list:
[0, 1, 2, 3, 4]
... and the elements in this list serve as the "indexes" in our results.
So let's do the same thing with our enumerate() version:
words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
print enumerate(words)
This certainly doesn't give us a list:
<enumerate object at 0x7f6be7f32c30>
...so let's turn it into a list, and see what happens:
print list(enumerate(words))
It gives us:
[(0, 'aba'), (1, 'xyz'), (2, 'xgx'), (3, 'dssd'), (4, 'sdjh')]
These are actual key/value pairs.
So this ...
words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
for i in range(len(words)):
print "words[{}] = ".format(i), words[i]
... actually takes the first list (Words), and creates a second, simple list of the range indicated by the length of the first list.
So we have two simple lists, and we are merely printing one element from each list in order to get our so-called "key/value" pairs.
But they aren't really key/value pairs; they are merely two single elements printed at the same time, from different lists.
Whereas the enumerate () code:
for i, word in enumerate(words):
print "words[{}] = {}".format(i, word)
... also creates a second list. But that list actually is a list of key/value pairs, and we are asking for each key and value from a single source -- rather than from two lists (like we did above).
So we print the same results, but the sources are completely different -- and handled completely differently.
Videos
Hello, I am currently working on a python script and I have a list that stores a block of comments (see below)
//################
//# [file id number]
//#################
//# [file name]
//#################
//#################
//# {file description}
//# {file description continues...}
//# {file description continues...}
//# {file description continues...}
//#################
//# [some more comments]
//# [some more comments]
//# [some more comments]
//##################Each line is its own string, and it stored in a list. I need to extract only certain blocks. For example
//################# //# [file name] //#################
and
//################# //# [some more comments] //# [some more comments] //# [some more comments] //##################
need to be extracted. Is there a way I can loop through the list and only extract those portions? I was going to do something along the lines of
for i in list:
if (i == "//####... "):
....The only problem with doing this is that there can be an arbitrary number of hashtags in each line, so i cannot hard code that, and there are multiple lines that have similar properties which means that the loop would be grabbing more then I need. Any help would be great!
You can replace all of this with index = a_list.index(search_term).
Note that if the list doesn't contain the search_term, it will throw an exception, so you'll need to catch that and return "not found" or something similar. Second note: it only returns the first index of the found search_term.
if search_term in a_list[i]: is True even if search_term is contained in a_list[i].
So in the case of an exact match index works, but in a case of a partial match index throws an exception.
Aside: elif not search_term in a_list: is wrong. Remove it or you'll return at first non-match.
Rewrite it as:
def get_element_number(a_list, search_term):
try:
return a_list.index(search_term)
except IndexError:
'no match'
This is simpler and has the advantage of performing search only once, which is important performance-wise when you're using linear search (not taking the overhead of exception into account).
Hi there,
how can i iterate through such a list? thanks in advance!
lst = ['nonoffensive', ['What', 'in', 'the', 'actual', 'fuck', '?', '#mkr'], ['#mkr',