Predefined Functions: Length
The Length predefined function allows a user to get the number of characters in a string or the number of items within an array.
The length can be assigned to a variable or used within a condition.
Key Points
Length can count the characters in a string.
Length can count the items in an array.
Length can be assigned to a variable.
Length can be used within a condition.
How to use Length
To use Length, you must write ‘length’ followed by two brackets. Inside the brackets, you must pass a parameter.
The parameter must either be a string or an array.
In the below example, the output would be 5 – the number of characters in the word “Hello”.
word = "Hello" print(len(word))
In this example, the output would be 3 – the number of items within the array.
fruit = ["Apple", "Pear", "Strawberry"] print(len(fruit))
Using Length within a condition
The Length of a string or an array can be used within a condition.
The following examples show two different approaches.
The below example first stores the length of a variable before using the variable in the condition.
word = "Hello"
length_of_word = len(word)
if length_of_word == 5:
print("The word has 5 characters!")
Additionally, the length can be used directly within the condition.
word = "Hello"
if len(word) == 5:
print("The word has 5 characters!")