len(): Count Elements in an Object

len(iterable )
iterable :input iterable or string or any sequence
Return the number of elements present, for string we can get number of chars in the string.

Using string

my_str='plus2net.com'
print(len(my_str)) #12
Using list
my_list=['Welcome','to','plus2net']
print(len(my_list)) # 3
my_list=[2,3,1,5]
print(len(my_list)) #4
Using tuple
my_tuple=(5,2,3,6)
print(len(my_tuple)) #4
Using Dictionary

Output depends on Keys of the Dictionary ( Not Values ).
my_dict={1:'A',2:'B',3:'C'}
print(len(my_dict)) # 3 
Using set
my_set={2,4,1,5}
print(len(my_set)) # 4
Using frozenset()
my_set={4,3,2,1,7}
my_set=frozenset(my_set)
print(len(my_set))  # 5 

Example 1: Counting Characters in a String

text = "plus2net"
print(len(text))  # Output: 8

Example 2: Length of a List

The function can also count elements in a list.
numbers = [1, 2, 3, 4, 5]
print(len(numbers))  # Output: 5

Example 3: Length of a Nested List

`len()` only counts the top-level items, not nested structures.
nested_list = [1, [2, 3], 4, [5, 6]]
print(len(nested_list))  # Output: 4

Example 4: Counting Key-Value Pairs in a Dictionary

Use `len()` to determine the number of entries in a dictionary.
data = {"name": "Alice", "age": 25, "location": "Paris"}
print(len(data))  # Output: 3

Applications of len()

  • Data Analysis: Quickly find the number of items in lists, dictionaries, or other collections.
  • Input Validation: Ensure string lengths or collection sizes meet specific criteria.
  • Loop Control: Use len() to set iteration limits based on collection size.

max() Iterator any()


Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer