In this tutorial, we will learn how to find the length of various data types in Python, such as strings, lists, tuples, and dictionaries. Finding the length of an object is a common task in programming and Python provides a built-in function called len() to achieve this.
Step 1: Finding the length of a string
We’ll start with a string. In Python, a string is a sequence of characters enclosed in single or double quotes. To find the length of a string, use the len() function, and pass the string as the argument.
Example:
1 2 3 |
text = "Hello, World!" length = len(text) print("The length of the string is:", length) |
Output:
The length of the string is: 13
Step 2: Finding the length of a list
A list in Python is an ordered collection of items enclosed in square brackets []. The len() function can also be used to find the length of a list.
Example:
1 2 3 |
fruits = ['apple', 'banana', 'cherry', 'orange', 'grape'] length = len(fruits) print("The length of the list is:", length) |
Output:
The length of the list is: 5
Step 3: Finding the length of a tuple
A tuple in Python is similar to a list but immutable, i.e., once assigned, its elements cannot be changed. Tuples are enclosed in round brackets (). To find the length of a tuple, use the len() function, and pass the tuple as the argument.
Example:
1 2 3 |
coordinates = (32, 45, 67, 29, 90) length = len(coordinates) print("The length of the tuple is:", length) |
Output:
The length of the tuple is: 5
Step 4: Finding the length of a dictionary
A dictionary in Python is an unordered collection of key-value pairs enclosed in curly braces {}. To find the length of a dictionary, use the len() function and pass the dictionary as the argument.
Example:
1 2 3 4 5 6 7 8 |
student = { 'name': 'John', 'age': 20, 'city': 'New York', 'course': 'Python' } length = len(student) print("The length of the dictionary is:", length) |
Output:
The length of the dictionary is: 4
Full code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
text = "Hello, World!" length = len(text) print("The length of the string is:", length) fruits = ['apple', 'banana', 'cherry', 'orange', 'grape'] length = len(fruits) print("The length of the list is:", length) coordinates = (32, 45, 67, 29, 90) length = len(coordinates) print("The length of the tuple is:", length) student = { 'name': 'John', 'age': 20, 'city': 'New York', 'course': 'Python' } length = len(student) print("The length of the dictionary is:", length) |
Output:
The length of the string is: 13 The length of the list is: 5 The length of the tuple is: 5 The length of the dictionary is: 4
Conclusion
In this tutorial, we learned how to find the length of different data types in Python, such as strings, lists, tuples, and dictionaries, using the built-in len() function. This function is quite versatile and can be used with various iterable objects to simplify handling and processing them.