Python is a powerful and versatile programming language with a wide range of handy features.
One of these features is the ability to iterate, or loop, through a list of words. This is a useful technique that can make your code more compact and easier to read.
This tutorial will guide you through the process of iterating through a list of words in Python. Let’s get started!
Step 1: Create a List of Words
In Python, a list is a type of data structure that can store multiple items in a single variable. Items in a list are enclosed in square brackets and separated by commas. Here’s an example:
1 |
words = ['Python', 'is', 'awesome'] |
Step 2: Use the for Loop to Iterate Through the List
The for loop in Python is used to iterate over a sequence such as a list, tuple, string, or range. Here’s how you can use it to iterate through a list of words:
1 2 |
for word in words: print(word) |
This loop will print each word in the list to the console in order.
Step 3: Use the enumerate Function for More Control
If you want more control over your iteration, you can use the enumerate function. This function adds a counter to the list and returns it as an enumerate object, which you can then easily convert into a list of tuples:
1 2 |
for i, word in enumerate(words): print(f'Word {i+1}: {word}') |
This loop will not only print each word in the list but also keep track of their position in the list.
Full Code
1 2 3 4 5 6 7 |
words = ['Python', 'is', 'awesome'] for word in words: print(word) for i, word in enumerate(words): print(f'Word {i+1}: {word}') |
Output
Python is awesome Word 1: Python Word 2: is Word 3: awesome
Conclusion
As you can see, iterating through a list of words in Python is quite straightforward. With just a few lines of code, you can loop through all the items in a list and handle them however you want.