In this article, we will discuss different ways to print list items using a for-loop in Python.
Table Of Contents
Method 1: Print list items one by one
We can iterate over list using a for loop, and in operator. During iteration, we will print each element of list in a separate line. Let’s see an example,
listOfStrs = ['Hello', 'this', 'is', 'a', 'correct', 'way', 'to', 'code'] # Iterate over all elements in list, # and print them one by one for elem in listOfStrs: print(elem)
Hello this is a correct way to code
We printed each item of list in a separate line.
Method 2: Print list items with index positions
We can pass our list object to the enumerate() function. It yields a collection of pairs. Where, each pair contains an item from list, along with its index position. We can iterate over these pairs, and print each item of list with its index position in the list. Let’s see an example,
listOfStrs = ['Hello', 'this', 'is', 'a', 'correct', 'way', 'to', 'code'] # Iterate over all elements of list # along with thier index position, and # print each item with index for index, value in enumerate(listOfStrs): print(index, " :: ", value)
- Convert a List of Tuples to two Lists in Python
- Get First Column from List of Tuples in Python
- Check if Any element in List is in another list in Python
- Python : Check if a list contains all the elements of another list
0 :: Hello 1 :: this 2 :: is 3 :: a 4 :: correct 5 :: way 6 :: to 7 :: code
We printed each item of list with its index position.
Method 3: print list items based on condition
In this example, we will iterate over all elements of list, using a for loop. But we will print only those items, which statisfies a given condition. For example, we will print only those strings in list, which contains more than three characters.
listOfStrs = ['Hello', 'this', 'is', 'a', 'correct', 'way', 'to', 'code'] # iterate over all the strings in list, # and print only those strings which # have more than 3 characters for elem in listOfStrs: if len(elem) > 3: print(elem)
Hello this correct code
We printed only selected strings from the list i.e. strings with size for than three.
We learned about different ways to print list items in python. We convered ways to print list elements with index position, and also based on conditions. Thanks.