Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Understanding Python Core Data Types

Tech May 13 1

Integers

Starting with Python 3, the int and long types were merged into a single int type. The default memory size of an integer aligns with the system architecture (e.g., 32-bit or 64-bit). When an integer exceeds the system's default bounds, Python automatically promotes it and allocates additional memory.

Common integer ranges include:

  • Int8: [-128, 127]
  • Int16: [-32768, 32767]
  • Int32: [-2147483648, 2147483647]
  • Int64: [-9223372036854775808, 9223372036854775807]
  • UInt8: [0, 255]
  • UInt16: [0, 65535]
  • UInt32: [0, 4294967295]
  • UInt64: [0, 18446744073709551615]
val = 42
print(type(val)) # <class 'int'>

Floating-Point Numbers

Floating-point numbers represent decimal values. In Python, they can be expressed in decimal or exponential notation.

Decimal Notation

Standard decimal format requires a decimal point; otherwise, the value is treated as an integer.

val = 9.81
print(type(val)) # <class 'float'>

Exponential Notation

Exponential format uses e or E to separate the mantissa from the exponent (e.g., aEn equals a * 10^n). Even if the resulting value is an integer mathematically, the data type remains a float.

val = 2.5E-3  # 2.5 * 10^-3
tiny_val = 0.0000000000007
print(tiny_val) # 7e-13

large_val = 15E4  # 150000.0
print(large_val)  # 150000.0
print(type(large_val)) # <class 'float'>

Complex Numbers

Python natively supports complex numbers, consisting of a real and an imaginary part. The imaginary part uses j or J as a suffix.

c1 = 5 + 2j
c2 = 3 - 1.5j
print(type(c1)) # <class 'complex'>
print(c1 + c2)  # (8+0.5j)
print(c1 * c2)  # (18+0j)

Strings

Declaration

Strings can be declared using single, double, or triple quotes.

s1 = 'apple'
s2 = "banana"
s3 = '''cherry'''
s4 = """date"""
print(type(s1)) # <class 'str'>

Operations

Concatenation: Use the + operator.

result = "Hello" + " World"
print(result) # Hello World

Repetition: Use the * operator.

echo = "Hi" * 3
print(echo) # HiHiHi

Indexing: Access characters using square brackets.

word = "python"
print(word[2]) # t

Slicing: Extract substrings using [start:stop:step].

seq = "ABCDEFGHIJ"
print(seq[:4])     # ABCD
print(seq[2:7:2])  # CEG
print(seq[5:])     # FGHIJ
print(seq[-3:])    # HIJ

Lists

Lists are ordered, mutable collections enclosed in square brackets. They support indexing and can contain heterogeneous data types.

CRUD Operations

Create / Insert:

fruits = ["apple", "banana", "cherry"]
fruits[0:0] = ["mango"]
print(fruits) # ['mango', 'apple', 'banana', 'cherry']

Delete:

nums = ["1", "2", "3", "4", "5"]
del nums[1]       # Delete single element
del nums[0:3]     # Delete slice
del nums[::2]     # Delete odd-indexed elements

Update:

fruits = ["apple", "banana", "cherry"]
fruits[2] = "date"           # Update single
fruits[0:1] = ["fig", "grape"] # Update slice

Retrieve:

fruits = ["fig", "grape", "banana", "cherry"]
print(fruits[0])    # fig
print(fruits[-1])   # cherry
print(fruits[:2])   # ['fig', 'grape']

Iteration

for item in fruits:
    print(item)

Operators and Functions

Operator / FunctionDescription
+Concatenates two lists
*Repeats list elements
in / not inChecks for element membership
len()Returns the length
min() / max()Returns the smallest/largest element

Common Methods

MethodDescription
.append(x)Adds an element to the end
.extend([x, y])Adds multiple elements
.insert(i, x)Inserts element at index i
.pop(i)Removes and returns element at index i (defaults to last)
.remove(x)Removes the first occurrence of x
.clear()Empties the list
.index(x)Returns the first index of x
.count(x)Counts occurrences of x
.reverse()Reverses the list in place
.sort(reverse=True)Sorts the list (descending if reverse=True)

Tuples

Tuples are ordered, immutable sequences defined using parentheses. Parentheses can be omitted except when defining a single-element tuple, which requires a trailing comma.

data = ("alpha", "beta", "gamma")
print(type(data)) # <class 'tuple'>
print(data[1:3])  # ('beta', 'gamma')

Sets

Sets are unordered collections of unique elements, created using curly braces. They do not support indexing.

MethodDescription
.add(x)Adds an element
.pop()Removes an arbitrary element
.remove(x)Removes a specific element
.clear()Empties the set
users = {"alice", "bob", "charlie"}
users.add("dave")
users.remove("bob")
print(users) # {'alice', 'charlie', 'dave'}
users.clear()
print(users) # set()

Dictionaries

Dictionaries store data as key-value pairs. Keys must be unique and of an immutable type (like strings or tuples).

CRUD Operations

Add:

profile = {"name": "Alice", "age": 25}
profile["city"] = "New York"

Delete:

del profile["city"]

Update:

profile["name"] = "Bob"

Retrieve:

print(profile.get("age")) # 25
print(profile["name"])      # Bob

Common Methods

MethodDescription
.popitem()Removes and returns an arbitrary pair
.pop(key)Removes the specified key
.clear()Empties the dictionary
.keys()Returns all keys
.values()Returns all values
.items()Returns all key-value pairs

Boolean Type

The Boolean type represents truth values with two constants: True and False.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.