Home  >  Article  >  Backend Development  >  Little knowledge you must master--detailed explanation of Python len examples

Little knowledge you must master--detailed explanation of Python len examples

零下一度
零下一度Original
2017-05-23 14:50:462316browse

Description

The Python len() method returns the length or number of items of an object (character, list, tuple, etc.).

Syntax

len() method syntax:

len( s )

Return value

Returns the length of the object.

Example

The following example shows the use of len():

>>>str = "runoob">>> len(str)             # 字符串长度6>>> l = [1,2,3,4,5]>>> len(l)               # 列表元素个数5

len is called when calling len(instance). len is a built-in function that returns the length of an object. It can be used for any object that is thought to have a deserving length.

The len of a string is the number of its characters; the len of a dictionary is the number of its keywords; the len of a list or sequence is the number of elements. For class instances, define the len method, and then compile it yourself...

In SQLite3, to query the number of results of the select statement, you cannot directly use the len(res) statement. You need to assign the fetchall method of the cursor to a array, and then use the len method on the data. The specific examples are as follows:

   import sqlite3
        conn = sqlite.connect('test.db')    cursor = conn.cursor()    cursor.execute("select uid, username, userpwd from member")    records = cursor.fetchall()
    num = len(records)

[Related recommendations]

1. In-depth understanding of the special function __len__(self) in python

2. Summarize the usage examples of len() function in Python

3. Used by python special class method Example tutorial

4. Python magic methods __getitem__, __setitem__, __delitem__, and __len__ are introduced respectively

The above is the detailed content of Little knowledge you must master--detailed explanation of Python len examples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn