Basics

Data Types in Python with Examples

funczun 2024. 10. 28. 10:28
Numeric Types
  • int: Integer values
a = 10
b = -28

result = a + b
print(result)
-18
  • float: Floating point values
a = 0.0
b = -10.28

result = a - b
print(result)
10.28
  • complex: Complex numbers
a = 1 + 2j
b = 3 - 4j

result = a * b
print(result)
(11+2j)

 In Python, the use of j instead of i can help avoid confusion because i is often used as a variable name.

 

Sequence Types
  • str: Strings
text = "Try Anything, Come True"

print(text[:12])
Try Anything
  • list: Ordered, mutable collections
languages = ["Java", "JavaScript"]

languages.append("Python")
print(languages)
['Java', 'JavaScript', 'Python']
  • tuple: Ordered, immutable collections
coordinates = (37.53, 126.98)

print(coordinates[0])
37.53

 Many programming languages ​​use zero-based indexing on various data structures to maintain consistency across languages.

 

Set Types
  • set: Unordered collections of unique elements
unique_numbers = {1, 2, 3, 2, 1}

print(unique_numbers)
{1, 2, 3}
  • frozenset: Immutable sets
immutable_set = frozenset([1, 2, 3, 2, 1])

print(immutable_set)

# use iteration instead of an index
for item in immutable_set:
    print(item)
frozenset({1, 2, 3})
1
2
3

 Although you cannot access a specific element of a set through an index, you can check whether an element in the set exists or iterate over the elements.

 

Mapping Type
  • dict: Key-value pairs
person = {"name": "funczun", "age": 26}
person["age"] = 24

print(person["name"])
print(person)
funczun
{'name': 'funczun', 'age': 24}

 Keys must be unique, but values ​​can be duplicates.

 

Boolean Type
  • bool: Represents True or False
is_valid = True
is_invalid = False

print(is_valid and is_invalid)
False

 In programming, and returns True only when both conditions are True.

 

None Type
  • NoneType: Represents the absence of a value
value = None

# use is instead of ==
if value is None:
    print("Value is None")
Value is None

 When comparing None, using == may produce unexpected results, so it is recommended to use the is operator.

 

Binary Types
  • bytes: Immutable sequences of bytes
byte_data = b'Hello'
b = bytes([65, 66, 67])

print(byte_data)
print(b)
b'Hello'
b'ABC'
  • bytearray: Mutable sequences of bytes
b = bytearray([65, 66, 67])

b[0] = 66
print(b)
bytearray(b'BBC')
  • memoryview: A view on a bytes like object
b = bytearray(b'BBC')

mv = memoryview(b)
print(mv[:1])
<memory at 0x0000016B07F5C7C0>

 When converting bytes to str, it must be decoded in the same manner as the specific encoding method used toconvert str to bytes.