What does len in python do

Python len()

The len() function returns the number of items (length) in an object.

Example

languages = ['Python', 'Java', 'JavaScript'] 
# compute the length of languages length = len(languages)
print(length) # Output: 3

len() Syntax

len() Parameters

The len() function takes a single argument s, which can be

  • sequence — string, bytes, tuple, list, range OR,
  • collection — dictionary, set, frozen set

len() Return Value

len() function returns the number of items of an object.

Failing to pass an argument or passing an invalid argument will raise a TypeError exception.

Example 1: 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))
[] length is 0 [1, 2, 3] length is 3 (1, 2, 3) length is 3 Length of range(1, 10) is 9

Visit these pages to learn more about:

Example 2: 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))
Length of is 0 Length of Python is 6 Length of b'Python' is 6 Length of b'\x01\x02\x03' is 3

Visit these pages to learn more about:

Example 3: How len() works with dictionaries and sets?

testSet = 
print(testSet, 'length is', len(testSet))
# Empty Set testSet = set() print(testSet, 'length is', len(testSet)) testDict =
print(testDict, 'length is', len(testDict))
testDict = <> print(testDict, 'length is', len(testDict)) testSet = # frozenSet frozenTestSet = frozenset(testSet)
print(frozenTestSet, 'length is', len(frozenTestSet))
 length is 3 set() length is 0 length is 2 <> length is 0 frozenset() length is 2

Visit these pages to learn more about:

Internally, len() calls the object’s __len__ method. You can think of len() as:

Читайте также:  Java call sql query

So, you can assign custom length to the object (if necessary)

Example 4: 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))

Источник

What is len() in Python? How to Use the len() Function to Find the Length of a String

Kolade Chris

Kolade Chris

What is len() in Python? How to Use the len() Function to Find the Length of a String

In programming languages, getting the length of a particular data type is a common practice.

Python is no different because you can use the built-in len() function to get the length of a string, tuple, list, dictionary, or any other data type.

In this article, I’m going to show you how to get the length of a string with the len() function.

Basic Syntax for len() in Python

To use the len() function to get the length of a data type, assign the data type to a variable, then pass the variable name to the len() function.

How to Find the Length of a String with the len() Function

When you use the len() function to get the length of a string, it returns the number of characters in the string – including the spaces.

Here are 3 examples to show you how it works:

name = "freeCodeCamp" print(len(name)) # Output: 12 

This means there are 12 characters in the string.

founder = "Quincy Larson" print(len(founder)) # Output: 13 

This means there are 13 characters in the string.

description = "freeCodeCamp is a platform for learning how to code for free" print(len(description)) # Output: 60 

This means there are 60 characters in the string.

How len() Works with Other Data Types in Python

You might be wondering how the len() function works on other data types such as lists and tuples.

When you use the len() function on a data type like tuple or list, it returns the number of items in the tuple or list, not the number of characters.

For example, 3 gets returned for the length of the tuple below, not the number of characters of the words in it.

langs = ("Python", "JavaScript", "Golang") print(len(langs)) # Output: 3 

So it just depends on the data type you’re working with.

Conclusion

In this article, you learned how to get the length of a string – the number of characters.

Kolade Chris

Kolade Chris

Web developer and technical writer focusing on frontend technologies. I also dabble in a lot of other technologies.

Читайте также:  Power function in cpp

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.

Источник

Why Does Python Have a len() Function?

Why Does Python Have a len() Function?

New Python users are often surprised to learn that you call a global function named len() to get the number of items in a container.

For example, if you’re used to a language like Ruby or Java, you might expect a Python list to have a length() method, but no – to get a list’s length, you call len(my_list) .

Now, of course, beauty is subjective. But why does Python use this approach instead of giving lists and other containers a length() method?

The longer answer is that len() makes asking how many items a container has consistent from the surface – len() – down through the implementation, which is done via a special __length__() method.

Let’s take a look at how this works and why it’s better than approaches in Java and Ruby, to use two popular examples.

The Surface

The main reason that len() works so well and has remained part of the Python language is that it provides a consistent surface interface to check the number of things an object contains.

Because len() is part of the language, we know what to expect from its input and output. Whatever “the number of things” means in the context of the object we pass to len() , we know we’ll get an integer result.

That’s all well and good, you might say, but isn’t the object just implementing some kind of length() method that len() calls for us?

In fact, that’s exactly what happens. To work with len() , your class needs to implement a __length__() method.

This simple indirection leads to a deeper consistency: all containers implement the same method to answer this question.

Читайте также:  Стилизация select css пример

Deep Consistency

Let’s quickly look at how to find the number of items in different container classes in Java and Ruby.

  • How do you find the number of items in an Array in Java?
  • How about an ArrayList ?
  • What about the same questions for an Array in Ruby?
  • How about the number of characters in a String in Ruby?
  • Array.length() (Java)
  • ArrayList.size() (Java)
  • Array.length , Array.size , or Array.count (Ruby)
  • String.length , String.size , but not String.count (Ruby)

Well, that’s confusing compared with Python, in which len() handles all of these cases.

Java and Ruby both have interfaces and mixins, respectively, that describe objects that have a size or length, but neither approach is as consistent as Python’s. For example, in Ruby, String doesn’t use the Enumerable mixin and thus doesn’t have a count() method like Array .

irb(main):001:0> x = "hey" => "hey" irb(main):002:0> x.count Traceback (most recent call last): 3: from /home/andrew/.rbenv/versions/2.5.0/bin/irb:11:in `' 2: from (irb):2 1: from (irb):2:in `count' ArgumentError (wrong number of arguments (given 0, expected 1+)) 

So String has a count() method, but it doesn’t do what you might expect, given how count() works with Enumerable objects. Instead of giving us the number of characters in the string, count() takes a string as an argument and counts occurrences of the input string in the target string.

Have I argued the point enough? Languages that use only interfaces or mixins lack the clarity that Python has with len() and __length__() .

Protocols

So what does Python do differently?

Ultimately, the difference is the combination of a built-in function, len() , with a consistently-used implementation method, __length__() .

There’s even more to the story, though.

The magic method __length__() forms a very simple “protocol.”

A protocol in Python is an informal interface. Practically speaking, it’s a set of methods that begin and end with double-underscores that define some behavior like iteration.

User-defined classes that implement all of the methods of a protocol can hook into system behavior through built-in functions like range() and syntax like for . in .

I have enough to say about protocols – and especially Python 3.8’s new structural subtyping mechanism – to fill another blog post, so for now I’ll leave it at that.

Check back soon for my next post on Python protocols and protocol classes!

Источник

Оцените статью