|
1 | 1 | --- |
2 | 2 | Title: 'len()' |
3 | | -Description: 'Returns the length of an object, which can either be a sequence or collection.' |
| 3 | +Description: 'Returns the number of items in an object.' |
4 | 4 | Subjects: |
5 | 5 | - 'Computer Science' |
6 | 6 | - 'Data Science' |
7 | 7 | Tags: |
| 8 | + - 'Data Types' |
8 | 9 | - 'Functions' |
9 | | - - 'Methods' |
10 | 10 | - 'Strings' |
11 | 11 | CatalogContent: |
12 | 12 | - 'learn-python-3' |
13 | 13 | - 'paths/computer-science' |
14 | 14 | --- |
15 | 15 |
|
16 | | -The built-in `len()` function returns the length of an object, which can either be a sequence or collection. |
| 16 | +The **`len()`** function returns the number of items in an object. It is one of Python's most commonly used built-in functions that calculates the length or size of various data types including [strings](https://www.codecademy.com/resources/docs/python/strings), [lists](https://www.codecademy.com/resources/docs/python/lists), [tuples](https://www.codecademy.com/resources/docs/python/tuples), [dictionaries](https://www.codecademy.com/resources/docs/python/dictionaries), [sets](https://www.codecademy.com/resources/docs/python/sets), and other sequence or collection types. |
| 17 | + |
| 18 | +The `len()` function is essential for determining the size of data structures, validating input lengths, implementing loops and iterations, and performing boundary checks in algorithms. It works with any object that has a defined length, making it a versatile tool for data manipulation and analysis tasks. |
17 | 19 |
|
18 | 20 | ## Syntax |
19 | 21 |
|
20 | 22 | ```pseudo |
21 | 23 | len(object) |
22 | 24 | ``` |
23 | 25 |
|
24 | | -An `object` passed to the `len()` function is commonly one of the following: |
| 26 | +**Parameters:** |
| 27 | + |
| 28 | +- `object`: A sequence (such as a string, list, tuple) or collection (such as a dictionary, set) whose length is to be calculated. |
| 29 | + |
| 30 | +**Return value:** |
25 | 31 |
|
26 | | -- It can be a sequence such as a [string](https://www.codecademy.com/resources/docs/python/strings) or [tuple](https://www.codecademy.com/resources/docs/python/tuples). |
27 | | -- It can also be a collection such as a [dictionary](https://www.codecademy.com/resources/docs/python/dictionaries) or [set](https://www.codecademy.com/resources/docs/python/sets). |
| 32 | +An integer value indicating the number of items in the object. |
28 | 33 |
|
29 | | -## Example |
| 34 | +## Example 1: Basic Usage |
30 | 35 |
|
31 | | -The example below demonstrates how the `len()` function is used in a Python program: |
| 36 | +The following example demonstrates the fundamental usage of `len()` with different data types: |
32 | 37 |
|
33 | 38 | ```py |
34 | | -print(len("Hello, World!")) |
35 | | -# Output: 13 |
| 39 | +# String length |
| 40 | +greeting = "Hello, World!" |
| 41 | +string_length = len(greeting) |
| 42 | +print(f"String length: {string_length}") |
| 43 | + |
| 44 | +# List length |
| 45 | +fruits = ["apple", "banana", "cherry", "date"] |
| 46 | +list_length = len(fruits) |
| 47 | +print(f"List length: {list_length}") |
| 48 | + |
| 49 | +# Tuple length |
| 50 | +coordinates = (10, 20, 30) |
| 51 | +tuple_length = len(coordinates) |
| 52 | +print(f"Tuple length: {tuple_length}") |
| 53 | + |
| 54 | +# Dictionary length (counts key-value pairs) |
| 55 | +student_grades = {"Alice": 95, "Bob": 87, "Charlie": 92} |
| 56 | +dict_length = len(student_grades) |
| 57 | +print(f"Dictionary length: {dict_length}") |
| 58 | +``` |
| 59 | + |
| 60 | +This example results in the following output: |
| 61 | + |
| 62 | +```shell |
| 63 | +String length: 13 |
| 64 | +List length: 4 |
| 65 | +Tuple length: 3 |
| 66 | +Dictionary length: 3 |
| 67 | +``` |
| 68 | + |
| 69 | +The `len()` function counts characters in strings, elements in lists and tuples, and key-value pairs in dictionaries. Each data type returns the count of its contained items. |
| 70 | + |
| 71 | +## Example 2: Input Validation |
| 72 | + |
| 73 | +The following example shows how to use `len()` for validating user input in real-world scenarios: |
| 74 | + |
| 75 | +```py |
| 76 | +def validate_username(username): |
| 77 | + """Validate username length requirements.""" |
| 78 | + min_length = 3 |
| 79 | + max_length = 20 |
| 80 | + |
| 81 | + username_length = len(username) |
| 82 | + |
| 83 | + if username_length < min_length: |
| 84 | + return f"Username too short. Minimum {min_length} characters required." |
| 85 | + elif username_length > max_length: |
| 86 | + return f"Username too long. Maximum {max_length} characters allowed." |
| 87 | + else: |
| 88 | + return "Username length is valid." |
| 89 | + |
| 90 | +# Test the validation function |
| 91 | +test_usernames = ["ab", "john_doe", "this_username_is_way_too_long_for_our_system"] |
| 92 | + |
| 93 | +for username in test_usernames: |
| 94 | + result = validate_username(username) |
| 95 | + print(f"Username '{username}' (length: {len(username)}): {result}") |
| 96 | +``` |
| 97 | + |
| 98 | +This example results in the following output: |
| 99 | + |
| 100 | +```shell |
| 101 | +Username 'ab' (length: 2): Username too short. Minimum 3 characters required. |
| 102 | +Username 'john_doe' (length: 8): Username length is valid. |
| 103 | +Username 'this_username_is_way_too_long_for_our_system' (length: 43): Username too long. Maximum 20 characters allowed. |
36 | 104 | ``` |
37 | 105 |
|
38 | | -## Codebyte Example |
| 106 | +This demonstrates how `len()` is commonly used in form validation, password requirements, and data quality checks in web applications and user interfaces. |
39 | 107 |
|
40 | | -In the example below, the `len()` function is used to return the length of a string, dictionary, and [list](https://www.codecademy.com/resources/docs/python/lists): |
| 108 | +## Codebyte Example: Data Processing Pipeline |
| 109 | + |
| 110 | +The following example illustrates using `len()` in a data processing scenario to analyze and filter datasets: |
41 | 111 |
|
42 | 112 | ```codebyte/python |
43 | | -trainer_name = "Code Ninja" |
| 113 | +def analyze_survey_responses(responses): |
| 114 | + """Analyze survey responses and filter by completion rate.""" |
| 115 | + total_responses = len(responses) |
| 116 | +
|
| 117 | + # Filter responses by completion (assuming responses with 5+ answers are complete) |
| 118 | + complete_responses = [response for response in responses if len(response) >= 5] |
| 119 | + incomplete_responses = [response for response in responses if len(response) < 5] |
| 120 | +
|
| 121 | + completion_rate = (len(complete_responses) / total_responses) * 100 |
| 122 | +
|
| 123 | + print(f"Survey Analysis Report:") |
| 124 | + print(f"Total responses received: {total_responses}") |
| 125 | + print(f"Complete responses: {len(complete_responses)}") |
| 126 | + print(f"Incomplete responses: {len(incomplete_responses)}") |
| 127 | + print(f"Completion rate: {completion_rate:.1f}%") |
44 | 128 |
|
45 | | -badges = { |
46 | | - "pewter city": "boulder badge", |
47 | | - "cerulean city": "cascade badge", |
48 | | - "vermillion city": "thunder badge" |
49 | | -} |
| 129 | + return complete_responses |
50 | 130 |
|
51 | | -pokemon_team = ["Pikachu", "Charmander", "Pidgeotto"] |
| 131 | +# Sample survey data (each inner list represents answers from one respondent) |
| 132 | +survey_data = [ |
| 133 | + ["Yes", "No", "Maybe", "Yes", "No"], # Complete (5 answers) |
| 134 | + ["Yes", "Yes"], # Incomplete (2 answers) |
| 135 | + ["No", "Maybe", "Yes", "No", "Yes", "Maybe"], # Complete (6 answers) |
| 136 | + ["Yes"], # Incomplete (1 answer) |
| 137 | + ["No", "No", "Yes", "Maybe", "No"], # Complete (5 answers) |
| 138 | + ["Maybe", "Yes", "No"] # Incomplete (3 answers) |
| 139 | +] |
52 | 140 |
|
53 | | -print(len(trainer_name)) |
54 | | -print(len(badges)) |
55 | | -print(len(pokemon_team)) |
| 141 | +complete_data = analyze_survey_responses(survey_data) |
56 | 142 | ``` |
| 143 | + |
| 144 | +This example shows how `len()` is used in data analysis workflows to calculate completion rates, filter datasets, and generate statistical reports commonly found in business intelligence and research applications. |
| 145 | + |
| 146 | +## Frequently Asked Questions |
| 147 | + |
| 148 | +### 1. What is the output of `len([1, 2, 3])`? |
| 149 | + |
| 150 | +The output is `3` because the list contains three elements. |
| 151 | + |
| 152 | +### 2. Can `len()` be used with empty objects? |
| 153 | + |
| 154 | +Yes, `len()` returns `0` for empty objects like empty strings `""`, empty lists `[]`, empty tuples `()`, and empty dictionaries `{}`. |
| 155 | + |
| 156 | +### 3. What happens if I use `len()` on None? |
| 157 | + |
| 158 | +Using `len(None)` raises a `TypeError` because `None` does not have a length. The object must be a sequence or collection type. |
0 commit comments