English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, you will learn about different data types that can be used in Python.
Each value in Python has a data type. Since everything in Python programming is an object, the data type is actually a class, and variables are instances (objects) of these classes.
Python has a variety of data types. The following lists some important types.
Integers, floating-point numbers, and complex numbers all belong to the category of Python numbers. In Python, they are defined as the int, float, and complex classes.
We can use the type() function to determine which class a variable or value belongs to. Similarly, the isinstance() function is used to check if an object belongs to a specific class.
a = 5 print(a, "is of type ", type(a)) a = 2.0 print(a, "is of type ", type(a)) a = 1+2j print(a, "is a complex number?", isinstance(1+2j, complex))
Output volume
5 is of type <class 'int'> 2.0 is of type <class 'float'> (1+2j) is a complex number? True
Integers can be of any length, but are limited by available memory.
Floating-point numbers can be precise up to 15 decimal places. Integers and floats are separated by a decimal point.1 is an integer,1.0 is a floating-point number.
complex numbers are written in the form x + written in the form yj, wherexis the real part,yis the imaginary part. Here are some examples.
>>> a = 1234567890123456789 >>> a 1234567890123456789 >>> b = 0.1234567890123456789 >>> b 0.12345678901234568 >>> c = 0. 1+2j >>> c (1+2j)
Note that the float variablebhas been truncated.
Listsis an ordered sequence of items. It is one of the most commonly used data types in Python and is very flexible. Items in a list can be of different types.
Declaring a list is very simple. Items separated by commas are placed within square brackets [ ].
a = [1, 2.2, 'python'
We can use the slicing operator [ ] to extract one item or a series of items from a list. Note that in Python, indexing starts from 0.
a = [5,10,15,20,25,30,35,40] # a[2]= 15 print("a[2]= "2}) # a[0:3]= [5, 10, 15] print("a[0:3]= "3}) # a[5:] = [30, 35, 40] print("a[5:] = "5:])
Output volume
a[2]= 15 a[0:3]= [5, 10, 15] a[5:] = [30, 35, 40]
Lists are mutable, which means the values of list elements can be changed.
a = [1, 2, 3] a[2]= 4 print(a)
Output volume
[1, 2, 4]
Tuples(Tuple) is an ordered sequence of items, similar to a list (List). The only difference is that tuples areImmutableOnce a tuple is created, it cannot be modified.
Tuples are used for write-protected data, usually faster than lists because they cannot be dynamically changed.
It is defined within parentheses (), with items separated by commas.
t = (5, 'program', 1+3j)
We can use the slicing operator [] to extract items, but we cannot change their values.
t = (5, 'program', 1+3j) # t[1)= 'program' print("t[1)= "1}) # t[0:3)= (5] = (1+3, 'program', ( print("t[0:3print("t[0:3}) # Produce error ] = ", t[0: File "test.py", line 10
Output volume
# Tuples are immutable1t[ ] = 'program'3t[0:5] = (1+3, 'program', ( Traceback (most recent call last): j)) 11, in <module> File "test.py", line 10 t[0] =
Python stringsstrings
is a sequence of Unicode characters. We can use single quotes or double quotes to represent strings. We can use triple quotes ''' or """ to represent multiline strings. string''' s = "This is a string" s = '''A multiline string'''
Output volume
print(s) This is a string A multiline
string
Like lists and tuples, the slice operator [ ] can be used with strings. However, strings are immutable. ] = 'o'4s = 'Hello world!' ] = 'world'4print("s[4}) ] = 'o'6:11# s[ ] = 'world'6:11print("s[6:11}) ] = ", s[ # An error occurs ] =5# Strings are immutable in Python
Output volume
] =4] = 'd' ] =6:11s[ Traceback (most recent call last): File '<string>', line 11, in <module> ] =
Python Set Set
a = {5,2,3,1,4} # It is an unordered collection of unique items. Sets are enclosed in curly braces { } and separated by commas. The items in the set are unordered. # Output the set variable # Output the data type of a print(type(a))
Output volume
a =1, 2, 3, 4, 5} <class 'set'>
We can perform set operations on two sets, such as union, intersection. Sets have unique values. They eliminate duplicates.
a = {1,2,2,3,3,3} print(a)
Output volume
{1, 2, 3}
Since set is an unordered collection, indexing is not meaningful. Therefore, the slice operator [] does not work.
>>> a = {1,2,3} >>> a[1] Traceback (most recent call last): File '<string>', line 301, in runcode File '<interactive input>', line 1, in <module> TypeError: 'set' object does not support indexing
dictionaryis an unordered collection of key-value pairs.
When we have a large amount of data, we usually use it. Dictionaries are optimized for data retrieval. We must know the key of the retrieval value.
In Python, curly braces {} define dictionaries, where each item is in the form of key:value. The key and value can be of any type.
>>> d = {1: 'value','key':2} >>> type(d) <class 'dict'>
We can use keys to retrieve the corresponding values.
d = {1: 'value','key':2} print(type(d)) print("d[1]= "1]); print("d['key'] = ", d['key']); # Produce error print("d[2]= "2]);
Output volume
<class 'dict'> d[1]= value d['key'] = 2 Traceback (most recent call last): File '<string>', line 9, in <module> KeyError: 2
We can use different type conversion functions, such as conversions between different data types, such as int(), float(), str(), etc.
>>> float(5) 5.0
The conversion from float to int truncates the value (making it closer to zero).
>>> int(10.6) 10 >>> int(-10.6) -10
String conversion must include compatible values.
>>> float('2.5') 2.5 >>> str('25) '25' >>> int('1p') Traceback (most recent call last): File '<string>', line 301, in runcode File '<interactive input>', line 1, in <module> ValueError: invalid literal for int() with base 10: '1p'
We can even convert one sequence to another sequence.
>>> set([1,2,3}) {1, 2, 3} >>> tuple({5,6,7) (5, 6, 7) >>> list('hello') ['h', 'e', 'l', 'l', 'o']
To convert to a dictionary, each element must be paired:
>>> dict([[1,2],[3,4]) {1: 2, 3: 4} >>> dict([(3,26),(4,44)) {3: 26, 4: 44}