search
HomeBackend DevelopmentPython TutorialFive basic Python data types

Five basic Python data types

Mar 31, 2018 pm 05:12 PM
pythondatatype

Learning a language often starts with Hello World. However, the author believes that there is nothing extraordinary about outputting "Hello, World" in a black box. To see through the essence of things and become familiar with a language, you must understand its underlying layer, which is what we often say. This article starts with variable types in python.

Five standard data types

The data stored in memory can be of many types.

For example, a person's name can be stored using characters, age can be stored using numbers, hobbies can be stored using sets, etc.

Python has five standard data types:

  • Numbers (numbers)

  • String (string)

  • List (list)

  • Tuple (element Group)

  • Dictionary

The data types belonging to the collection type are Lists, tuples and dictionaries.

1. Numbers

Number data type is used to store numerical values.

They are immutable data types, which means that changing the numeric data type will allocate a new object.

When you specify a value, a Number object is created:

var1 = 1
var2 = 2

The del statement deletes references to some objects. The syntax is:

del var1[,var2[,var3[....,varN]]]]

By using the del statement References to single or multiple objects can be deleted. For example:

del var1
del var1, var2

Four different number types:

  • int (signed integer type)

  • long (long integer type [can also represent octal and hexadecimal])

  • float (floating point type)

  • complex (plural)

a. int (integer)

On a 32-bit machine, the number of digits in the integer is 32 bits. The value range is -2**31~2**31-1, that is, -2147483648~2147483647
On a 64-bit system, the number of digits in the integer is 64, and the value range is -2**63~2* *63-1, that is, -9223372036854775808~9223372036854775807

b. long (long integer)
Unlike C language, Python’s long integer does not specify the bit width, that is: Python There is no limit to the size of long integer values, but in fact due to limited machine memory, long integer values ​​cannot be infinitely large.
Note that since Python 2.2, if an integer overflow occurs, Python will automatically convert the integer data to a long integer, so now not adding the letter L after the long integer data will not cause serious consequences.

c. float (floating point type)

Floating point numbers are used to process real numbers, that is, numbers with decimals. Similar to the double type in C language, it occupies 8 bytes (64 bits), of which 52 bits represent the base, 11 bits represent the exponent, and the remaining bit represents the symbol.
d. complex (plural number)
A complex number consists of a real part and an imaginary part. The general form is x+yj, where x is the real part of the complex number and y is the imaginary part of the complex number. Here x and y are both real numbers.

Note: There is a small number pool in Python: -5 ~ 257

Small integer object - small integer object pool

In actual programming , relatively small integers, such as 1, 2, 29, etc., may appear very frequently. In python, all objects exist on the system heap. Think about it? If a small integer appears very often, Python will have a large number of malloc/free operations, which greatly reduces operating efficiency and causes a large amount of memory fragmentation, seriously affecting the overall performance of Python.

In Python 2.5 and even 3.3, small integers between [-5,257) are cached in the small integer object pool.

2. String

String or String It is a string of characters composed of numbers, letters, and underscores.

It is a data type that represents text in programming languages.

Python's string list has two value orders:

  • The index starts from left to right by default 0, and the maximum range is 1 less than the string length

  • The right-to-left index starts from -1 by default, and the maximum range is the beginning of the string

If you want to get a section from the string For strings, you can use the variable [head subscript:tail subscript] to intercept the corresponding string. The subscript starts from 0 and can be a positive or negative number. The subscript can Empty means getting to the beginning or end.

For example: the result of

s = 'i love python'

s[2:6] is love. (Consider the head but not the tail, or close the left and open the right)

Operation example:

str = 'Hello World'
 
print(str)                 #输出完整字符串
print(str[0])              #输出字符串中的第一个字符
print(str[2:5])            #输出字符串中第三个至第五个之间的字符
print(str[2:])             #输出从第三个开始到最后的字符串
print(str*2)               #输出字符串两次
print('say: ' + str)       #输出连接的字符串

3. List (List)

List is the most frequently used data type in Python.

列表可以完成大多数集合类的数据结构实现。List里面的数据类型也可以不同,它支持字符,数字,字符串甚至可以包含列表(所谓嵌套)。

操作实例:  

list =  ['apple', 'jack', 798, 2.22, 36]
otherlist = [123, 'xiaohong']
 
print(list)                             #输出完整列表
print(list[0])                          #输出列表第一个元素
print(list[1:3])                        #输出列表第二个至第三个元素
print(list[2:])                         #输出列表第三个开始至末尾的所有元素
print(otherlist * 2)                    #输出列表两次
print(list + otherlist)                 #输出拼接列表

 

4. 元组(Tuple)

元组用"()"标识。

内部元素用逗号隔开。但是元组一旦初始化,就不能修改,相当于只读列表。

只有1个元素的tuple定义时必须加一个逗号 , ,来消除歧义(否则会认为t只是一个数):

>>> t = (1,)>>> t
(1,)

操作实例与列表相似

5. 字典(Dictionary)

字典(dictionary)是除列表以外Python之中最灵活的内置数据结构类型。列表是有序的对象结合,字典是无序的对象集合。

两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。

字典用"{ }"标识。字典由索引(key)和它对应的值value组成。

操作实例:

dict = {}
dict['one'] = 'This is one'
dict[2] = 'This is two'
tinydict = {'name':'john','code':5762,'dept':'sales'}
 
print(dict['one'])                          #输出键为'one'的值
print(dict[2])                              #输出键为2的值
print(tinydict)                             #输出完整的字典
print(tinydict.keys())                      #输出所有键
print(tinydict.values())                    #输出所有值

The above is the detailed content of Five basic Python data types. 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
What is Python Switch Statement?What is Python Switch Statement?Apr 30, 2025 pm 02:08 PM

The article discusses Python's new "match" statement introduced in version 3.10, which serves as an equivalent to switch statements in other languages. It enhances code readability and offers performance benefits over traditional if-elif-el

What are Exception Groups in Python?What are Exception Groups in Python?Apr 30, 2025 pm 02:07 PM

Exception Groups in Python 3.11 allow handling multiple exceptions simultaneously, improving error management in concurrent scenarios and complex operations.

What are Function Annotations in Python?What are Function Annotations in Python?Apr 30, 2025 pm 02:06 PM

Function annotations in Python add metadata to functions for type checking, documentation, and IDE support. They enhance code readability, maintenance, and are crucial in API development, data science, and library creation.

What are unit tests in Python?What are unit tests in Python?Apr 30, 2025 pm 02:05 PM

The article discusses unit tests in Python, their benefits, and how to write them effectively. It highlights tools like unittest and pytest for testing.

What are Access Specifiers in Python?What are Access Specifiers in Python?Apr 30, 2025 pm 02:03 PM

Article discusses access specifiers in Python, which use naming conventions to indicate visibility of class members, rather than strict enforcement.

What is __init__() in Python and how does self play a role in it?What is __init__() in Python and how does self play a role in it?Apr 30, 2025 pm 02:02 PM

Article discusses Python's \_\_init\_\_() method and self's role in initializing object attributes. Other class methods and inheritance's impact on \_\_init\_\_() are also covered.

What is the difference between @classmethod, @staticmethod and instance methods in Python?What is the difference between @classmethod, @staticmethod and instance methods in Python?Apr 30, 2025 pm 02:01 PM

The article discusses the differences between @classmethod, @staticmethod, and instance methods in Python, detailing their properties, use cases, and benefits. It explains how to choose the right method type based on the required functionality and da

How do you append elements to a Python array?How do you append elements to a Python array?Apr 30, 2025 am 12:19 AM

InPython,youappendelementstoalistusingtheappend()method.1)Useappend()forsingleelements:my_list.append(4).2)Useextend()or =formultipleelements:my_list.extend(another_list)ormy_list =[4,5,6].3)Useinsert()forspecificpositions:my_list.insert(1,5).Beaware

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software