How to print items from a list with specific length in Python
This tutorial will focus on how to print items from a list with a specific length in Python. So our goal will be as follows:
- We have a list with some items in it.
- We need to filter the items having a specific length.
- Then print the filtered items.
Filter items from a list with a specific length
Let’s understand this with an easy example.
Start with our example list:
my_list = ['dinner','python','computer','developer','programming']
Now as you can see there are several items in our list.
Now, you are said to find the items with a specific number of characters.
Suppose, you have to find the items having a specific length 8.
Algorithm to solve this:
- Read the list items in a for loop.
- In the for loop keep checking if the value of the item is equal to 8 or not.
- If any item found just print it.
Python code to print items from a list with a specific length
my_list = ['dinner','python','computer','developer','programming'] for i in my_list: if(len(i)) == 8: print(i)
Output:
$ python codespeedy.py computer
Among all the items in our list only the item “computer” is having a specific length 8, thus it prints “computer”.
Major function we have used:
len() function – len() function is an inbuilt function of Python.
Return type of len() function – It returns an integer value, which is the length of a string.
Parameter of len() function – We can pass string value as a parameter to get the length of the string.
Also, read other tutorials:
Leave a Reply