The len Function

Hey all, it’s me again! Learning about the len function this week in regard to strings (ie. print(len(firstName))).

I’m wondering when this would ever be a useful function to use. Obviously it’s a built-in function so it must have some important uses, but as somebody new to programming, I’m not sure I can think of any.

Thanks in advance!

Let’s say you’re writing a command-line utility which converts .foo
files to .bar format, and rather than using a complex argument
parser you just want to have the old and new filenames supplied as
bare arguments to the command. You may want to provide a useful
message to the user, like so:

if len(sys.argv) != 3:  # remember argv[0] includes the command name
    print("Please provide the names of both the foo and bar files!")

It’s a very simplistic example, but more generally, len() is useful
any time you want to find out if an iterable object contains fewer,
more than, or exactly sum number of items. Or, you might use it to
report the length of some object:

print("%s records loaded" % len(records.processed))

There are countless more uses, but maybe len() could count them for
you too! :wink:

Hey @fungi! Thanks for replying. I’ll be honest: that first block of code means nothing to me. I’m working on it and hopefully I’ll get there eventually, but still very new to coding (as is likely obvious from my lack of understanding of where len could be used.

With that said, your second one makes more sense to me, though I am wondering if you could confirm my understanding that records.processed would be a predefined/determined variable. Is that correct?

[…]

With that said, your second one makes more sense to me, though I
am wondering if you could confirm my understanding that
records.processed would be a predefined/determined variable.
Is that correct?

I imagined that records might be an instance object of some
fictional Records class with a class attribute named
processed of type list which got appended to after each
entry of some set of input data was processed. To be honest I didn’t
put a lot of thought into the example, it was just meant to
represent a situation where you might have some countable set of
data and you wanted to report the len() of it to a user. Maybe
they know how many records were supplied to the program, but didn’t
know that some of them were unable to be processed, or perhaps they
were deduplicated at the time they were stored, or… too many
possibilities really.

len() is one of the most useful functions. We probably use it more often
on lists than strings, but it gets used for strings very frequently too.

Suppose you want to take a string and underline it:

s = 'Hello world'
print(s + '\n' + '-'*len(s))

The string ‘\n’ is not a literal backslash followed by ‘n’, it is an
escape-code for a newline character. So the above code computes:

how many characters are in s?
make a row of dashes that many characters long
concatenate a newline and the row of dashes after s
and print it

Which will give us:

x        Hello world
x        -----------

(Please ignore the ‘x’ column, that is there to prevent the Discourse
software from deleting everything after the line of dashes.)

Another example:

password = input("Please enter your new password: ")
if len(password) < 10:
    print("Password is too short, please try another one.")

A lot of the time, the call to len() will be hidden inside other string
methods. For example, if you call one of the methods:

str.center
str.ljust
str.rjust

to align the string to a certain width, internally the method needs to
know how long the string is so it knows how much padding to use:

'Hello world'.center(20, '-')
# returns '----Hello world-----'

RealPython has a nice introduction to len():

https://realpython.com/len-python-function/

1 Like

Thanks so much, Erlend! I’ll take a look at that later today. Before I do, can you explain how len works in this scenario:

average = total / len(daily_revenues)

I know that len normally counts the length of a string…Does it effectively do the same in a list (as daily_revenues is)? Is len essentially saying:

average = total / [each number in list - daily_revenues]?

For lists len returns the number of items in the list (also known as «list size» or «list length»). Ditto for other types of sequences, such as tuples or strings.

Hi Ryan,

For many of your questions, you can get an answer by experimenting at
the interpreter.

Open a Python interpreter session so that you have the “>>>” prompt, and
try some experiments. Enter these at the >>> prompt:

daily_revenues = [10, 20, 30, 40, 50]
len(daily_revenues)

What do you expect it to return? What does it return?

You can also do this:

help(len)
1 Like

Hmmm… I don’t really know what you know, so I’ll try my best to make it as simple as possible.

len() is an very useful function. One way it can be used is to print each character of a string out.

Like this!

test = "Hello World"

for i in range(len(test)):
  print(test[i])

The len function tells the program how many characters are in the string. Without it it would try to read past the end of the function. Hope that makes sense!