How to Use Pythons Len Method

In this tutorial, python beginners and expert coders can easily learn how to use python’s len() method with different objects. Apart from this, you may also discover python len() examples with output in this Python len() function tutorial. Let’s find the length of an object by using this len() method and code perfectly in complex programs.

The Tutorial of Python len() Method includes the following stuff: 

Python String Length | Python len() Function

Python’s len() method can be used to easily find the length of a string. It’s a simple and quick way to measure the length of a string (the number of characters) without having to write a lot of code.

Syntax

The syntax of len() is:

len(s)

Parameters of the len()

The len() method doesn’t take any parameters other than the name of the string, so that’s the only thing that can be passed through it.

s – a sequence (string, bytes, tuple, list, or range) or a collection (dictionary, set, or frozen set)

It isn’t a particularly versatile method, but it does come in handy for this one specific purpose, and there are a number of different reasons you may come across in your coding adventures where you’ll need to find the length of a string. You can also use this method in if statement to execute certain code based on the number of characters a string has (or doesn’t have).

Return Value

The len() method returns an integer value ie., the length of the given string, or array, or list or collections.

Also Check: Using Python Display Calendars

How to use len() in Python?

To see how it works & uses, refer to the following snippet:

str = "hey, I'm a string, and I have a lot of characters...cool!"
print = "String length:", len(str)

So to find the length of the string “str”, you need to pass it through the len() method. Your answer will be the number of characters in the string, and that includes punctuation and spaces. The number of characters in the string “str” is 57, including the spaces, commas, periods, apostrophes, and exclamation points. So the output of the above code would be as follows:

String length: 57

The len() method will also count numbers along with spaces and punctuation if they’re included in a string, like in the example below:

str = "I'm 26 years old."
print = "String length:", len(str)

The output for the above code, in which the str string has 17 characters, including spaces, apostrophes, numbers, and a period, would be as follows:

String length: 17

Python len() Example

The following example on how to find the length of the given string defines the len() method.

# testing len() 
str1 = "Welcome to Pythonarray Tutorials"
print("The length of the string  is :", len(str1))

Output:

The length of the string is : 31

Internal Working of the len() Function in Python

The method of len() function len() truly works as a counter, that is automatically incremented as the data is determined and collected. Once you call the len() function, you do not provide the interpreter the command to obtain the length by traversing, but first, you ask the interpreter to print a value that is already stored. The len() function in Python runs in O(1) complexity. Therefore, it can also be defined as:

def length(ar):
   
    # calling the internally 
    # defined __len__() method
    return ar.__len__() 
  
# Driver code
a = [1, 2, 3, 4, 6]
print(length(a))

Output:

5

How len() works with tuples, lists, and range?

testList = []
print(testList, 'length is', len(testList))

testList = [1, 2, 3]
print(testList, 'length is', len(testList))

testTuple = (1, 2, 3)
print(testTuple, 'length is', len(testTuple))

testRange = range(1, 10)
print('Length of', testRange, 'is', len(testRange))

Output:

[] length is 0
[1, 2, 3] length is 3
(1, 2, 3) length is 3
Length of range(1, 10) is 9

How len() works for custom objects?

class Session:
    def __init__(self, number = 0):
      self.number = number
    
    def __len__(self):
      return self.number


# default length is 0
s1 = Session()
print(len(s1))

# giving custom length
s2 = Session(6)
print(len(s2))

Output:

0
6

How len() works with strings and bytes?

testString = ''
print('Length of', testString, 'is', len(testString))

testString = 'Python'
print('Length of', testString, 'is', len(testString))

# byte object
testByte = b'Python'
print('Length of', testByte, 'is', len(testByte))

testList = [1, 2, 3]

# converting to bytes object
testByte = bytes(testList)
print('Length of', testByte, 'is', len(testByte))

Output:

Length of is 0
Length of Python is 6
Length of b'Python' is 6
Length of b'\x01\x02\x03' is 3

How len() works with dictionaries and sets?

testSet = {1, 2, 3}
print(testSet, 'length is', len(testSet))

# Empty Set
testSet = set()
print(testSet, 'length is', len(testSet))

testDict = {1: 'one', 2: 'two'}
print(testDict, 'length is', len(testDict))

testDict = {}
print(testDict, 'length is', len(testDict))

testSet = {1, 2}
# frozenSet
frozenTestSet = frozenset(testSet)
print(frozenTestSet, 'length is', len(frozenTestSet))

Result:

{1, 2, 3} length is 3
set() length is 0
{1: 'one', 2: 'two'} length is 2
{} length is 0
frozenset({1, 2}) length is 2

Leave a Reply

Your email address will not be published.