Home/Blog/Python/Python Data Types | Strings Numbers Collections
Python

Python Data Types | Strings Numbers Collections

Master strings, numbers, collections, and datetime for effective programming

Python Data Types | Strings Numbers Collections

Strings and Characters

Strings and characters are fundamental data types in Python. A character is essentially a string with a single number, letter, or special character such as ‘!’ or ‘@’. A string is a collection of characters that may or may not form readable words and sentences.

name = "Python Programming"
character = "P"
print(name)  # Output: Python Programming
print(character)  # Output: P

Numbers

Python supports four main types of numbers:

  • Integer: Whole numbers without decimal points (e.g., 5, -3, 100)
  • Long Integer: Very large whole numbers
  • Float: Numbers with decimal points (e.g., 3.14, -2.5)
  • Complex: Numbers with real and imaginary parts
integer_num = 42
float_num = 3.14
complex_num = 2 + 3j

print(type(integer_num))  # <class 'int'>
print(type(float_num))    # <class 'float'>
print(type(complex_num))  # <class 'complex'>

Collections

Collections are data types used when you want to store multiple items. Python offers four main collection types:

  • List: Ordered, changeable, allows duplicates
  • Dictionary: Ordered, changeable, key-value pairs
  • Tuple: Ordered, unchangeable, allows duplicates
  • Set: Unordered, changeable, no duplicates
# List example
fruits = ["apple", "banana", "cherry"]

# Dictionary example
person = {"name": "John", "age": 30, "city": "New York"}

# Tuple example
coordinates = (10, 20)

# Set example
unique_numbers = {1, 2, 3, 4, 5}

Date and Time

Date time data types are used for dates and times. While you can store dates as strings, using proper datetime objects provides built-in functionality for formatting, arithmetic, and manipulation.

from datetime import datetime, timedelta

# Current date and time
now = datetime.now()
print(now)

# Add one day
tomorrow = now + timedelta(days=1)
print(tomorrow)

# Format date
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date)

Advantage: Using datetime objects instead of strings gives you automatic date arithmetic, formatting options, and timezone handling.

Frequently Asked Questions

Find answers to common questions

Python provides built-in functions for type conversion: str() converts to strings and int() converts to integers. To convert integers to strings, use str(number), which is useful for concatenation or formatted output. To convert strings to integers, use int(string_number), but ensure the string represents a valid integer or a ValueError will be raised. Handle conversion errors with try-except blocks to gracefully manage invalid input. Best practices include: always validating input before conversion (use regular expressions to check for numeric characters); using try-except blocks when converting user input; avoiding implicit conversions between incompatible types, as Python requires explicit conversions to prevent unexpected results. For example, in a web application receiving age input as a string, wrap the conversion in a try-except block: try: age = int(age_input) to store in the database, except ValueError: handle the invalid input appropriately. This approach ensures robust applications with proper error handling and type management.

Lists and dictionaries are fundamental Python collection types serving different purposes. Lists are ordered collections defined with square brackets, indexed by position starting from zero, ideal for maintaining sequences where order matters (user inputs, task queues) and supporting iteration, sorting, and appending. Dictionaries are unordered collections of key-value pairs defined with curly braces, accessed using unique keys rather than indices, perfect for associating values with keys (user profiles, configurations, entity mappings). Key differences: lists maintain order while dictionaries preserve insertion order only from Python 3.7+; lists use numerical indexing while dictionaries use key-based access; dictionaries offer faster lookups using hash tables compared to list searching. Use lists when you need sequential access, slicing, or aggregating items without enforcing uniqueness. Use dictionaries when you need fast key-based access and structured data storage with natural mappings. For example, track user activities using a list for action timestamps and a dictionary mapping user IDs to activity data. Choose the right type based on data nature: lists for order, dictionaries for quick lookups.

Python's datetime module provides robust tools for creating, manipulating, and formatting datetime objects. Create datetime objects using datetime.now() for current time or datetime(year, month, day, hour, minute) for specific dates. Format datetime objects into readable strings using strftime() with format codes like %Y (year), %m (month), %d (day), and %H (hour). Perform arithmetic operations using timedelta objects: add or subtract time periods with now + timedelta(days=10) or now - timedelta(days=5). Calculate differences between datetime objects, which returns a timedelta object with accessible attributes like days. Best practices include: always using datetime objects instead of strings for date manipulation to leverage built-in functionality; handling timezones with the pytz library when working across multiple zones (timezone.localize(now)); implementing error handling with try-except blocks when parsing strings to catch ValueError exceptions; and storing formatted timestamps in databases using strftime(). Mastering datetime manipulation is critical for applications requiring precise date and time handling, ensuring accurate computations and proper formatting throughout your code.

Automate Your IT Operations

Leverage automation to improve efficiency, reduce errors, and free up your team for strategic work.