Can len() be used with other types?

Yes, the len() function in Python can be used with several other types, including:

  1. Lists: Returns the number of elements in the list.

    my_list = [1, 2, 3]
    print(len(my_list))  # Output: 3
  2. Tuples: Returns the number of elements in the tuple.

    my_tuple = (1, 2, 3)
    print(len(my_tuple))  # Output: 3
  3. Dictionaries: Returns the number of key-value pairs in the dictionary.

    my_dict = {'a': 1, 'b': 2}
    print(len(my_dict))  # Output: 2
  4. Sets: Returns the number of unique elements in the set.

    my_set = {1, 2, 3}
    print(len(my_set))  # Output: 3
  5. Strings: As mentioned earlier, it returns the number of characters in the string.

The len() function is versatile and can be used with any object that implements the __len__() method. If you have more questions or need examples, let me know!

0 Comments

no data
Be the first to share your comment!