Basic Data Types in Python

Introduction to Python Data Types

This lecture explores the core components of Python’s data handling capabilities, focusing on how and why these types are used in data science.

Types of Data in Python

Python categorizes data into two main types:

  • Values: Singular items like numbers or strings.

  • Collections: Groupings of values, like lists or dictionaries.

Mutable vs Immutable

  • Mutable: Objects whose content can be changed after creation.

  • Immutable: Objects that cannot be altered after they are created.

Overview of Main Data Types

Category Mutable Immutable
Values - int, float, complex, str
Collections list, dict, set, bytearray tuple, frozenset

Numeric Types

Integers (int)

  • Use: Counting, indexing, and more.
  • Construction: x = 5
  • Immutable: Cannot change the value of x without creating a new int.

Numeric Types (continued)

Floating-Point Numbers (float)

  • Use: Representing real numbers for measurements, fractions, etc.
  • Construction: y = 3.14
  • Immutable: Like integers, any change creates a new float.

Text Type

Strings (str)

  • Use: Handling textual data.
  • Construction: s = "Data Science"
  • Immutable: Modifying s requires creating a new string.

Sequence Types

Lists (list)

  • Use: Storing an ordered collection of items.
  • Construction: my_list = [1, 2, 3]
  • Mutable: Items can be added, removed, or changed.

Sequence Types (continued)

Tuples (tuple)

  • Use: Immutable lists. Often used where a fixed, unchangeable sequence is needed.
  • Construction: my_tuple = (1, 2, 3)
  • Immutable: Cannot alter the contents once created.

Set Types

Sets (set)

  • Use: Unique collection of items, great for membership testing, removing duplicates.
  • Construction: my_set = {1, 2, 3}
  • Mutable: Can add or remove items.

Set Types (continued)

Frozen Sets (frozenset)

  • Use: Immutable version of sets.
  • Construction: my_frozenset = frozenset([1, 2, 3])
  • Immutable: Safe for use as dictionary keys.

Mapping Types

Dictionaries (dict)

  • Use: Key-value pairs for fast lookup and data management.
  • Construction: my_dict = {'key': 'value'}
  • Mutable: Add, remove, or change associations.

Conclusion

Understanding these basic types is crucial for data handling and manipulation in Python, especially in data science where the type of data dictates the analysis technique. As we move into more advanced Python we will get to know more complex data types.

For more information, you can always refer to the Python official documentation.