- 1
So what are some ways to use âlenâ
SOO.. I KINDA KEEP FORGETTING ABOUT HOW YOU USE LEN IN A LINE OF CODE SO COULD YOU GUYS TELL ME ONE OF THE SIMPLIST, POSSIBLE WAYS TO USE LEN?
4 Answers
+ 3
THE len FUNCTION RETURNS THE NUMBER OF ITEMS IN AN ITERABLE. THE SIMPLEST POSSIBLE USE OF IT IS SOMETHING LIKE THIS:
print(len([1, 2, 3]))
+ 3
The function len() determines the length of a sequence or the number of elements. A sequence can be a string, list, tuple, set and dictionary. There can also be a mixture, so list can contain int values plus a string and so on
len('hello') # string
5
len([123,7,12]) # list
3
len(((1,2),(2,7),(0,1,2))) # a tuple that contains other tuple
3
len({1,4,45}) # set
3
len({1:'ab',2:'xbz'}) # dictionary
2
This is a simple code, that checks the length of the elements in a list. The elements don't have the same length, so they are processed to a common length of e.g. 6: (you can copy and paste this code and also execute it to see what happens)
inp = ['000045A1', '00000001B4', '001234X']
# bring input to a defined length = 6 chars starting at the very right side of each lement
max_len = 6
for i in inp: # this loop is for demonstration only
print(f'length of {i:{max([len(x) for x in inp])}} is {len(i):3}') # Edit
for i in inp: # this loop is processing the elements of the list
print(i[len(i) - max_len:])
+ 2
Let's do it in a different way: You tell us what you know about len(). This is such a simple function, i can not believe that you can forget it.
+ 1
I know that len counts how much numbers in a list or array but its just confusing how you use it like I mean, I just asking a simpler way you can use it a sentence