马口鱼是什么鱼| 肝血管瘤挂什么科| 芒果什么人不能吃| 什么是预科生| 九牛一毛指什么生肖| 东华帝君的真身是什么| 六味地黄丸有什么副作用吗| 6月5号什么星座| 孕妇吃什么蔬菜对胎儿好| 慢性浅表性胃炎伴糜烂吃什么药| 拉屎不成形是什么原因| 孕激素低吃什么补得快| 夏天喝什么| 田野是什么意思| 兰花长什么样| 这什么情况| 豫州是现在的什么地方| 呼吸不畅是什么原因| 宝宝体检挂什么科| 小白兔是什么意思| 艾叶泡水喝有什么功效| 老婆生日送什么鲜花| 白羊座是什么象星座| 黄油是用什么做的| boy是什么牌子| 什么是甲状腺| 生目念什么| 肺肿物是什么意思| 扁平疣用什么治疗| 胰岛素抵抗是什么意思| 强颜欢笑是什么意思| 老玻璃是什么意思| 头经常晕是什么原因| 第一次为什么进不去| add是什么意思| 中医内科主要看什么| 血钾低会有什么症状| 十五岁是什么年华| 疔是什么意思| 什么门永远关不上| 开户名是什么| 吃什么可以降血压| 正月二十是什么星座| 胰腺疼痛吃什么药| 拉不出大便吃什么药| 小鸡吃什么食物| 合拍是什么意思| 死心是什么意思| 吃素是什么意思| 泄是什么意思| 什么人容易得帕金森| 歧路亡羊告诉我们什么道理| 你的脚步流浪在天涯是什么歌曲| 中盐是什么盐| 女人大姨妈来了吃什么最好| 梦见打麻将是什么意思| 破伤风疫苗什么时候打| 维生素检查项目叫什么| 肝多发小囊肿什么意思| 为什么同房不怀孕原因| 9月13日是什么星座| 睡醒后口苦是什么原因| 有加有减先算什么| 肝胆胰脾彩超查什么病| 大便成细条状是什么病| 一劳永逸什么意思| 弱冠是什么意思| 组胺过敏是什么意思| 给事中是什么官| 五指毛桃什么人不能吃| 红红的太阳像什么| 高血脂是什么原因引起的| 芒果什么人不能吃| 膝盖响是什么原因| 急性子是什么意思| 莱昂纳多为什么叫小李子| 不什么好什么| 众矢之地是什么意思| 水灵灵是什么意思| 孕吐什么时候结束| 什么什么为笑| 老当益壮是什么意思| 太阳黑子是什么东西| 什么是反流性咽喉炎| 容易手麻脚麻是什么原因| 婴儿第一次理发有什么讲究吗| 治脚气用什么药| 玉谷叶是什么植物| 省委巡视组组长什么级别| 表水是什么意思| 体内湿热吃什么中成药| 月经期间吃什么水果| 杨桃是什么季节的水果| 什么的枝叶| 深海鱼都有什么鱼| 尿多是什么问题| 蛋白尿是什么| 晴字五行属什么| 为什么崴脚了休息一晚脚更疼| 泥鳅喜欢吃什么食物| 吃什么去黄褐斑最有效| 独角仙生活在什么地方| 六安瓜片属于什么茶| 爻卦是什么意思| 梦到很多蛇是什么意思| 王妃是什么意思| 白扁豆长什么样| 女儿红是什么酒| 内啡肽是什么| 1978年五行属什么| 吃生红枣有什么好处| 做梦掉牙齿是什么意思周公解梦| 梦见儿子拉屎是什么意思| 手足口病用什么药| 单脐动脉对胎儿有什么影响| 姜字五行属什么| 牙根痛吃什么药| 船只是什么意思| add是什么意思| 连长是什么级别| gln是什么氨基酸| 上甘岭在什么地方| 白狗子是什么意思| 千里马比喻什么样的人| 中央候补委员是什么级别| 猕猴桃什么时候成熟| 飞机杯什么感觉| 睡醒嘴苦是什么原因| 1991是什么年| 女人气血不足吃什么补| 什么匆匆| 宝石蓝是什么颜色| 失策是什么意思| 肝右叶钙化灶什么意思| 宫颈炎是什么病| 什么是自由度| 鹅蛋不能和什么一起吃| 八大菜系之首是什么菜| 什么的挑选| 悬脉是什么意思| 逼上梁山什么意思| 香蕉人是什么意思| 胸口疼是什么病的前兆| 今天属什么生肖日历| 尿糖弱阳性是什么意思| 甲状腺发炎有什么症状| 预约转账什么时候到账| 发烧吃什么退烧药| guava是什么水果| 妇科臭氧治疗的作用是什么| 吃醪糟有什么好处| 87年是什么年| 月经结束一周后又出血是什么原因| 掼蛋是什么意思| 耳朵痒是什么预兆| 奔跑吧 什么时候开播| 下面外面瘙痒用什么药| 什么的花灯| 什么是挂科| 三十六计第一计是什么| 四级士官是什么级别| 景德镇有什么好玩的| 8月18日什么星座| 什么叫唐卡| 什么茶刮油| 教师节送老师什么好| 月经下不来是什么原因| 尿液带血什么原因| 荠菜什么时候播种最好| 燕窝什么时候吃好| 松树像什么| s和m什么意思| 什么什么直跳| 户名是什么| 孩子干咳吃什么药效果好| 女人补肾吃什么药| 亚麻籽油和胡麻油有什么区别| 13年是什么年| 看静脉曲张挂什么科| 安哥拉树皮有什么功效| 悉如外人的悉是什么意思| 奶奶的姐姐叫什么| 血压高可以吃什么水果| 世界上什么东西最大| 咽炎什么症状| 狗男和什么属相最配| 系统b超主要检查什么| 靶子是什么意思| 什么叫间质性肺病| 火字旁的有什么字| 手上长痣代表什么| 便秘去药店买什么药吃| 结肠炎是什么症状| 查脂肪肝挂什么科室| 知世故而不世故是什么意思| 人为什么会胡思乱想| 返流性食管炎用什么药| 发癫是什么意思| 肚脐眼中间疼是什么原因| 女性检查生育挂什么科| 凤梨和菠萝的区别是什么| 什么是五险一金| 黄瓜炒什么好吃| 空调扇的冰晶是什么| 天空又什么又什么| 拉绿屎是什么原因| 甲亢可以吃什么水果| r值是什么| pwr是什么意思| 小燕子吃什么| 保肝降酶药首选什么药| 做雪糕需要什么材料| 山羊吃什么| 七个月宝宝能吃什么水果| 75年属什么| 结晶是什么意思| 致电是什么意思| 晟念什么字| 疼痛科属于什么科| 远视眼是什么意思| 脑膜炎是什么| 冬天吃什么水果| 甜蜜素是什么| 菜瓜是什么瓜| 313什么意思| 六月二十七是什么日子| 人工流产后可以吃什么| 熬夜眼睛红血丝用什么眼药水| 嘴唇发麻是什么病兆| 才思敏捷是什么意思| 霸凌是什么意思| 金鱼吃什么食物| 湿气重吃什么药最好| 什么情况下做喉镜| 饭中吃药是什么时候吃| 世五行属什么| 宫颈纳氏腺囊肿是什么意思| 孕前检查挂什么科| 朗字五行属什么| 尿液黄绿色是什么原因| 硬不起来是什么原因| 回字是什么结构| 大运正官是什么意思| 机化是什么意思| 男人为什么喜欢吸奶| 肝内囊性灶什么意思| 享福是什么意思| gd什么意思| 熟啤酒是什么意思| 血府逐瘀丸治什么病| 宦官是什么意思| 早上八点是什么时辰| 槟榔什么味道| 权字五行属什么| 烦躁是什么意思| 三心二意是指什么生肖| 儿童扁桃体发炎吃什么药| 女娲和伏羲是什么关系| 下午3点是什么时辰| 复方新诺明片又叫什么| 领略是什么意思| 文理分科什么时候开始| 什么什么发光| 口干舌燥吃什么食物好| 百度
Bytes

故宫停售“俏格格娃娃” 已售出的一律退款召回

Last Updated: 20th October, 2024
百度 这将是我国首次出台地热发展五年规划,地热开发利用料将进入高速发展的黄金时期。

Python offers several data types, including numbers (integers and floating-point), lists , dictionaries (for key-value pairs), booleans (True or False ), and sets (for unique values ). These data types help store and process data efficiently.

Data Types in Python-min.png

What are Data Types?

Saranya is a data scientist working on a project to gather and analyze data. As part of her analysis, she needed to understand the different data types she would be dealing with. Saranya came across a book ???? that contained information about the different data types.

The book explained that data could be classified as one of four types: integers , floats, strings ?? and booleans. Saranya discovered that an integer is a whole number like 3 or -25; a float is a number with decimals like 3.1415; strings are words or phrases contained within quotation marks like "Hello World"; and booleans can only have two possible values: true ? and false ?.

The book also explained how each type of data has its unique properties and how they can be used in various ways. For example, Saranya learned that integers could be added together to find the sum of two integers, but multiplying an integer by another integer will produce another integer. Saranya found a similar book ?? that talked about the types of data that can be classified as resources.

The resource type in the book is called a "resource locator" because it will tell Saranya where to find the resources she needs, which make up her project . Resources are divided into four categories: strings, floats, booleans, and dates . A string is a text contained within quotation marks like "Hello World," ?whereas booleans can only have two values: true or false . At the same time, dates are numerical representations of a specific date .

?? Did you Know ? In Python, the data types are also classified based on their mutability. Mutable data types can be changed after creation, while immutable data types cannot be changed after creation.

Different Data Types in Python

Python is a high-level, object-oriented programming language that provides a wide range of data types to aid in developing numerous applications.

List of Python Data Types

  • Numeric Data Types
  • Sequence Data Types
  • Mapping Data Types
  • Dictionaries in Python
  • Booleans in Python
  • Binary Types
  • Sets in Python
  • None Type
CategoryData TypeDescription
Numeric TypesintIntegers of unlimited size.
?floatFloating-point numbers (decimal numbers).
?complexComplex numbers in the form a + bj.
Sequence TypeslistMutable sequences, typically used to store collections.
?strImmutable sequences of Unicode characters (strings).
?tupleImmutable sequences, used to store collections.
?rangeImmutable sequences of numbers, commonly used for looping.
Mapping TypedictMutable mappings of keys to values (dictionaries).
Set TypessetUnordered collections of unique elements (mutable).
?frozensetImmutable versions of sets.
Boolean TypeboolBoolean values True or False.
Binary TypesbytesImmutable sequences of bytes.
?bytearrayMutable sequences of bytes.
?memoryviewMemory views of binary data without copying it.
None TypeNoneTypeRepresents the absence of a value (None).

Understand the Data Types in Python with Examples

1. Numeric Data types

Numeric data types are data types that represent numbers, such as integers and floating point numbers. They are used in programming and databases to store and manipulate numerical values. The most common numeric data types in Python are:

  1. integers: whole numbers without decimals, positive or negative, of unlimited length
  2. floating point numbers: numbers with decimals, positive or negative, of limited length
  3. complex numbers: combinations of real and imaginary numbers, like a + bj

int (Integer)

Example:

# Create integers
positive_int =?42
negative_int =?-99
large_int =?12345678901234567890

# Arithmetic operations
sum_int = positive_int + negative_int
print("Sum:", sum_int)

# Check the type
print(type(positive_int))

Output:

Sum:?-57
<class 'int'>

float (Floating-Point Number)

Example:

# Create floats
pi =?3.14159
negative_float =?-2.71828

# Arithmetic operations
product = pi * negative_float
print("Product:", product)

# Check the type
print(type(pi))

Output

Product:?-8.539721265199999
<class 'float'>

complex (Complex Number)

Example:

# Create complex numbers
complex_num1 =?2 +?3j
complex_num2 =?5 -?4j

# Arithmetic operations
sum_complex = complex_num1 + complex_num2
print("Sum:", sum_complex)

# Access real and imaginary parts
print("Real part:", complex_num1.real)
print("Imaginary part:", complex_num1.imag)

# Check the type
print(type(complex_num1))

Output:

Sum: (7-1j)
Real part:?2.0
Imaginary part:?3.0
<class 'complex'>

2. Sequence Data Types in Python

In Python, sequence data types refer to objects that hold a collection of items, such as strings, lists, and tuples. These objects can be indexed and sliced and have various methods for modifying and manipulating their contents.

  1. Strings: Strings are sequences of characters enclosed in single or double quotes.
  2. Lists: Lists are ordered lines of values enclosed in square brackets. They can include any data type.
  3. Tuples: Tuples are immutable, ordered sequences of values defined using parentheses.

str (String)

Example:

# Create a string
greeting =?"Hello, World!"
print(greeting)

# Access individual characters
first_char = greeting[0]
print("First character:", first_char)

# String concatenation
new_greeting = greeting +?" How are you?"
print(new_greeting)

# Check the type
print(type(greeting))

Output:

Hello, World!
First character: H
Hello, World! How are you?
<class 'str'>

List

Example:

# Create a list
fruits = ['apple',?'banana',?'cherry']

# Access elements
print("First fruit:", fruits[0])

# Modify elements
fruits[1] =?'blueberry'
print("Modified list:", fruits)

# Add elements
fruits.append('date')
print("Extended list:", fruits)

# Check the type
print(type(fruits))

Output:

First fruit: apple
Modified list: ['apple',?'blueberry',?'cherry']
Extended list: ['apple',?'blueberry',?'cherry',?'date']
<class 'list'>

Tuple

Example:

# Create a tuple
coordinates = (10.0,?20.0)

# Access elements
x = coordinates[0]
y = coordinates[1]
print(f"X: {x}, Y: {y}")

# Attempting to modify elements (will raise an error)
try:
? ? coordinates[0] =?5.0
except TypeError?as e:
? ? print("Error:", e)

# Check the type
print(type(coordinates))

Output:

X:?10.0, Y:?20.0
Error:?'tuple' object does?not support item assignment
<class 'tuple'>

Range

  • An immutable sequence of numbers, commonly used for looping a specific number of times in for-loops.
  • The range() function generates a sequence of numbers, which can be iterated over. It is memory-efficient because it generates numbers on the fly.

Example:

# Create a range
numbers = range(5)

# Convert range to list for display
number_list = list(numbers)
print("Number list:", number_list)

# Iterate over range
for i?in range(3,?8):
? ? print("Number:", i)

# Check the type
print(type(numbers))

Output:

Number list: [0,?1,?2,?3,?4]
Number:?3
Number:?4
Number:?5
Number:?6
Number:?7
<class 'range'>

3. Dictionaries in Python

A dictionary in Python is an unordered set of key-value pairs. Keys identify elements in the dictionary . Values can be any Python object. Dictionaries are mutable , changeable, and indexed for easy, fast access and modification . Dictionaries map keys to values like a dictionary maps words to definitions .

Syntax:

Loading...

Examples:

Loading...

4. Booleans in Data Types in Python

In Python, booleans represent either True or False values. They are crucial for controlling program flow with conditional statements like if and else.

Bool

Example:

# Boolean values
is_active =?True
is_closed =?False

# Logical operations
result = is_active?and?not is_closed
print("Result:", result)

# Boolean from expressions
comparison =?10 >?5
print("10 > 5:", comparison)

# Check the type
print(type(is_active))

Output:

Result:?True
10 >?5:?True
<class 'bool'>

5. Sets in Python

  • Sets in Python are unordered collections of unique elements. ?They are mutable and useful for storing and manipulating unique, unordered data.?
  • Sets enable set operations like union, intersection, difference, and symmetric difference. They are useful in mathematics and for removing duplicates from sequences.?
  • Sets are?mutable, meaning they can be changed. However, they remain unordered and unindexed.

Set

Example:

# Create a set
unique_numbers = {1,?2,?3,?2,?1}
print("Unique numbers:", unique_numbers)

# Add elements
unique_numbers.add(4)
print("After adding 4:", unique_numbers)

# Set operations
set_a = {1,?2,?3}
set_b = {3,?4,?5}
union_set = set_a.union(set_b)
intersection_set = set_a.intersection(set_b)
print("Union:", union_set)
print("Intersection:", intersection_set)

# Check the type
print(type(unique_numbers))

Output:

Unique numbers: {1,?2,?3}
After adding?4: {1,?2,?3,?4}
Union: {1,?2,?3,?4,?5}
Intersection: {3}
<class 'set'>

Frozenset

  • An immutable version of a set.
  • Once a frozenset is created, you cannot change its elements. Useful when you need a constant set of unique elements.

Example:

# Create a frozenset
frozen_set = frozenset([1,?2,?3,?2,?1])
print("Frozen set:", frozen_set)

# Attempting to modify (will raise an error)
try:
? ? frozen_set.add(4)
except AttributeError?as e:
? ? print("Error:", e)

# Set operations
set_c = {2,?3,?4}
union_frozen = frozen_set.union(set_c)
print("Union with set:", union_frozen)

# Check the type
print(type(frozen_set))

Output:

Frozen set: frozenset({1,?2,?3})
Error:?'frozenset' object has no attribute?'add'
Union?with set: frozenset({1,?2,?3,?4})
<class 'frozenset'>

6. Binary Types

bytes:

  • An immutable sequence of bytes (integers in the range 0 ≤ x < 256).
  • Used for binary data, such as files or network resources. Bytes literals are prefixed with b.

Example:

# Create bytes
byte_data =?b'Hello, Bytes!'
print("Byte data:", byte_data)

# Access elements
first_byte = byte_data[0]
print("First byte:", first_byte)

# Iterate over bytes
for b?in byte_data:
? ? print(b, end=' ')
print()

# Check the type
print(type(byte_data))

Output:

Byte data:?b'Hello, Bytes!'
First byte:?72
72?101?108?108?111?44?32?66?121?116?101?115?33?
<class 'bytes'>

bytearray:

  • A mutable sequence of bytes.
  • Similar to bytes, but mutable. Useful when you need to modify binary data.

Example:

# Create bytearray
mutable_bytes = bytearray(b'Hello')
print("Original bytearray:", mutable_bytes)

# Modify elements
mutable_bytes[0] = ord('h')
print("Modified bytearray:", mutable_bytes)

# Convert to bytes
bytes_converted = bytes(mutable_bytes)
print("Converted to bytes:", bytes_converted)

# Check the type
print(type(mutable_bytes))

Output:

Original bytearray: bytearray(b'Hello')
Modified bytearray: bytearray(b'hello')
Converted to bytes:?b'hello'
<class 'bytearray'>

memoryview:

  • A memory-efficient view of another binary object’s data without copying it.
  • Allows you to access the buffer protocol of an object. Useful for large data manipulation.

Example:

# Create a bytearray
data = bytearray('ABC',?'utf-8')
print("Original data:", data)

# Create a memoryview
view = memoryview(data)
print("Memoryview:", view)

# Modify data through memoryview
view[1] = ord('Z')
print("Modified data:", data)

# Check the type
print(type(view))

Output:

Original data: bytearray(b'ABC')
Memoryview: <memory at?0x7f...>
Modified data: bytearray(b'AZC')
<class 'memoryview'>

Note: The memory address in the memoryview output (<memory at 0x7f...>) will vary each time you run the code.

7. None Type

  • The type of the None object, which represents the absence of a value.
  • None is often used to signify 'no value' or 'empty' and is the default return value of functions that do not explicitly return anything.

Example:

result =?None

8. Mapping Type

dict (Dictionary)

Example:

# Create a dictionary
person = {'name':?'Alice',?'age':?30,?'city':?'New York'}

# Access values
print("Name:", person['name'])

# Modify values
person['age'] =?31
print("Updated person:", person)

# Add new key-value pair
person['email'] =?'alice@example.com'
print("Extended person:", person)

# Iterate over keys and values
for key, value?in person.items():
? ? print(f"{key}: {value}")

# Check the type
print(type(person))

Output:

Name: Alice
Updated person: {'name':?'Alice',?'age':?31,?'city':?'New York'}
Extended person: {'name':?'Alice',?'age':?31,?'city':?'New York',?'email':?'alice@example.com'}
name: Alice
age:?31
city: New York
email: alice@example.com
<class 'dict'>

Additional Notes on Data Types in Python

Immutability vs. Mutability:

  • Immutable types cannot be changed after creation (e.g., str, tuple, frozenset, bytes).
  • Mutable types can be changed (e.g., list, dict, set, bytearray).

Type Checking:

You can check the type of a variable using the type() function.

type_variable = type(42)? # Returns <class 'int'>

Dynamic Typing:

Python uses dynamic typing, meaning variables can change type during execution.

var =?10? ? ??# var is an int
var =?'ten' ??# var is now a str

Custom Data Types:

You can create your own data types using classes.

class?Person:
? ??def?__init__(self, name):
? ? ? ? self.name = name

The types Module:

The types module provides names for built-in types that aren't directly accessible.

import types
function_type = types.FunctionType

Conclusion

Saranya has understood different data types in Python, such as numeric, sequence, dictionary, boolean, and set. She can work with these data types to analyze data and draw meaningful insights. She is familiar with the basic operations of each data type and can use them for her data science projects.

Key Takeaways

  1. Python has various built-in data types, including integers, floats, strings, booleans, lists, tuples, dictionaries, and sets.
  2. Each data type has a specific purpose and should be used for the appropriate task.
  3. Integers represent whole numbers. Floats represent real numbers. Strings represent text. Booleans represent truth values. Lists represent collections of values. Tuples represent immutable collections of values. Dictionaries define key-value pairs. Sets represent collections of unique values.
  4. Type conversion can convert one data type into another.
  5. When working with data, remember to consider the data types used and ensure they suit the task.

Quiz

  1. Which of the following is a data type in Python?
    1. String?
    2. Integer?
    3. Float?
    4. All of the above

Answer: D. All of the above

  1. What data type would you use to store a list of values?
    1. Integer?
    2. Float?
    3. String
    4. List

Answer: D. List

  1. What data type would you use to store a single character? ?
    1. Integer?
    2. Float?
    3. String?
    4. Boolean

Answer: C. String

Module 4: Data Structures in PythonData Types in Python (With Examples)

Top Tutorials

Related Articles

  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

? 2025 AlmaBetter
序列是什么意思 卵巢结节是什么意思 茄子与什么食物相克 06年属什么 行政许可是什么意思
什么是灌肠 抽血血液偏黑什么原因 钟鸣鼎食是什么意思 xxoo什么意思 四大皆空是什么生肖
百合什么意思 鱼字五行属什么 火腿肠炒什么好吃 骨折什么意思 1月8日是什么星座
男性睾丸一边大一边小是什么原因 5月12是什么星座 什么时间吃水果最好 肺部结节是什么引起的 双开是什么意思
转氨酶偏高是什么意思hcv8jop5ns5r.cn 下身瘙痒用什么药hcv8jop5ns9r.cn 水逆是什么hcv9jop7ns5r.cn 蚊子有什么用hcv8jop8ns8r.cn 便秘吃什么润肠通便hcv8jop9ns1r.cn
天煞是什么意思hcv9jop5ns3r.cn 血稠吃什么药最好wzqsfys.com 红眼病吃什么药hcv9jop0ns0r.cn 但愿人长久的下一句是什么hcv9jop6ns6r.cn 生化妊娠后需要注意什么hcv9jop1ns9r.cn
梦见房子是什么意思jasonfriends.com 诺如病毒通过什么传染hcv8jop6ns5r.cn 1893年属什么生肖hcv8jop4ns9r.cn 煮虾放什么调料hcv8jop5ns3r.cn 开塞露加什么能去皱纹wuhaiwuya.com
二月二十是什么星座hcv8jop9ns6r.cn 西药是用什么材料做的hcv7jop9ns6r.cn 枫树叶子像什么hcv8jop8ns3r.cn 小狗拉肚子吃什么药onlinewuye.com 唐僧被封为什么佛creativexi.com
百度