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 Overflow
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ iterating over a list of strings
r/learnpython on Reddit: iterating over a list of strings
April 18, 2022 -

I'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.

Top answer
1 of 9
57

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])
2 of 9
3

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.

๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_lists_loop.asp
Python - Loop Lists
Remove List Duplicates Reverse a String Add Two Numbers ยท Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... Learn more about for loops in our Python For Loops Chapter. You can also loop through the list items by referring to their index number.
๐ŸŒ
Statistics Globe
statisticsglobe.com โ€บ home โ€บ python programming language for statistics & data science โ€บ loop through list of strings in python (3 examples)
Loop Through List of Strings (with Index) in Python (3 Examples)
August 1, 2023 - In this example, we have a list of strings called names. The for loop iterates over each element in the list, and we print the values of name. The second example demonstrates how to loop through a list of strings and access both the value and index of each element.
๐ŸŒ
Sololearn
sololearn.com โ€บ en โ€บ Discuss โ€บ 2812980 โ€บ how-can-i-use-while-loop-to-iterate-through-lists-or-strings-if-i-dont-want-to-use-the-for-in-loop-in-python
How can I use while loop to iterate through lists or strings if I don't want to use the for in loop in python? | Sololearn: Learn to code for FREE!
For example : a = [i for i in range(11)] # this can be done also putting the numbers one to one j = 0 while j < len(a): i = a[j] print(i) j+=1 In this situation the while loop is evaluating the j variable to not be same as length of a. So j represents the index of elements of a. Before the increment of j, you can operate as you want with values of a thanks to i. So it is possible to use while instead of for but for iterate directly in a list, rather getting them with index. But try more with the for loop if you have a finite collection of values, and while for infinite ones or those which you don't know the limit ๐Ÿ˜€. The Zen of Python : "Simple is better than complex ...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how can i loop through list of strings and extract certain indices that match the string?
r/learnpython on Reddit: How can I loop through list of strings and extract certain indices that match the string?
July 18, 2022 -

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!

๐ŸŒ
Quora
quora.com โ€บ How-does-a-for-loop-work-with-lists-and-strings-in-Python
How does a for loop work with lists and strings in Python? - Quora
Answer (1 of 3): In some ways itโ€™s silly to ask how for loops work with specific data types. In Python for loops work with any collection of objects as well as any dynamic generator of objects (generator expressions, and iterators). Such collections are referred to as โ€œiterablesโ€ (objects which ...
Find elsewhere
๐ŸŒ
Llego
llego.dev โ€บ home โ€บ blog โ€บ a comprehensive guide to iterating through lists, strings, and tuples using for loops in python
A Comprehensive Guide to Iterating through Lists, Strings, and Tuples using For Loops in Python - llego.dev
May 24, 2023 - This prints only the first 4 characters of the string. break and continue work in string iteration as well: name = "John" for char in name: if char == 'h': break print(char) for char in name: if char in 'aeiou': continue print(char) The first loop breaks early once โ€˜hโ€™ is encountered, while the second loop skips vowels. Tuples are immutable sequences in Python. Iterating through tuples works exactly like lists:
๐ŸŒ
Python Guides
pythonguides.com โ€บ python-loop-through-a-list
How To Iterate Through A List In Python?
September 20, 2024 - A while loop can also be used to iterate through a list in Python, although itโ€™s less common than the for loop. The while loop continues as long as a specified condition is true. ... cities = ["New York", "Los Angeles", "Chicago", "Houston"] index = 0 while index < len(cities): print(cities[index]) index += 1 ... List comprehension is a concise way to create lists and iterate through them. It is often used for creating new lists by applying an expression to each item in an existing list.
๐ŸŒ
LearnPython.com
learnpython.com โ€บ blog โ€บ python-list-loop
7 Ways to Loop Through a List in Python | LearnPython.com
However, this time we used list comprehension to do two things: add the word โ€˜juiceโ€™ to the end of the list item and print it. Another method for looping through a Python list is the range() function along with a for loop.
๐ŸŒ
Quora
quora.com โ€บ In-Python-how-can-I-loop-through-a-list-and-append-all-of-its-values-to-a-string-variable
In Python, how can I loop through a list and append all of its values to a string variable? - Quora
Answer (1 of 2): The un-Pythonic way, akin to something youโ€™d do in C or C++: [code]l = [...] s = "" for item in l: s += str(item) [/code]The Python way: [code]l = [...] s = "".join(map(str, l)) [/code]
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ python โ€บ ways to loop through a list in python
Ways to Loop Through a List in Python - Spark By {Examples}
May 31, 2024 - If you are in a hurry, below are some quick examples of the looping-through list. # Quick examples of looping list # Initialize list courses = ["Python", "Spark", "pandas", "Java"] # Example 1: Iterate over list # Using for loop for item in courses: print(item) # Example 2: Using for loop and range() for i in range(len(courses)): print(courses[i]) # Example 3: Iterate over list # Using a while loop index = 0 while index < len(courses): print(courses[index]) index = index + 1 # Example 4: Using enumerate() function for index, value in enumerate(courses): print(index, ":", value) # Example 5: Us
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ iterate-over-a-list-in-python
Iterate over a list in Python - GeeksforGeeks
Here we are using a while loop to iterate through a list. We first need to find the length of list using len(), then start at index 0 and access each item by its index then incrementing the index by 1 after each iteration.
Published ย  December 27, 2025
๐ŸŒ
Gitbooks
buzzcoder.gitbooks.io โ€บ codecraft-python โ€บ content โ€บ string โ€บ loop-through-a-string.html
Loop through a string ยท CodeCraft-Python
The len() function is a Python ... ยท Here we show two ways to iterate over characters in a string: One way to iterate over a string is to use for i in range(len(str)):. In this loop, the variable i receives the index so that each character can be accessed using str...
๐ŸŒ
Dot Net Perls
dotnetperls.com โ€บ for-python
Python - for: Loop Over String Characters - Dot Net Perls
for c in s: print(c) # Loop over string indexes. for i in range( ... A for-loop acts upon a collection of elements, not a min and max. In for, we declare a new variable.
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ python โ€บ python iterate over list
Python Iterate Over List - Spark By {Examples}
May 31, 2024 - By using this for loop syntax you ... objects (string, list, tuple, set, range, or dictionary(dict)). A list contains a collection of values so, we can iterate each value present in the list using Python for loop or while loop. In this article, you will learn different ways to iterate through a Python ...