Python内置函数`len()`可以返回列表、元组、字典、集合、字符串以及range对象中元素的个数。以下是一些示例代码,展示了`len()`函数在不同数据结构中的应用:
1. **对于列表**:
```python
my_list = [1, 2, 3, 4, 5]
print(len(my_list)) # 输出: 5
```
2. **对于元组**:
```python
my_tuple = (1, 2, 3, 4, 5)
print(len(my_tuple)) # 输出: 5
```
3. **对于字典**:
```python
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(len(my_dict)) # 输出: 3
```
4. **对于集合**:
```python
my_set = {1, 2, 3, 4, 5}
print(len(my_set)) # 输出: 5
```
5. **对于字符串**:
```python
my_string = "hello"
print(len(my_string)) # 输出: 5
```
6. **对于range对象**:
```python
my_range = range(10)
print(len(my_range)) # 输出: 10
```
这些示例代码展示了`len()`函数能够返回各种数据结构中的元素个数,满足用户询问的功能需求。