Python List Data Types - Detailed Explanation
=============================================
In Python, a list is an ordered, mutable (changeable) collection of elements. Lists can store elements
of any data type, and even a mixture of different data types.
1. Numbers
----------
Numbers are one of the most common data types stored in lists.
- Integers (int): Whole numbers, positive or negative, without a decimal point.
Example: [1, 2, -5, 100]
- Floating point numbers (float): Numbers that contain a decimal point.
Example: [1.5, 2.75, -3.14]
- Complex numbers (complex): Numbers with a real and imaginary part.
Example: [2+3j, 4-5j]
2. Strings (str)
----------------
Strings are sequences of characters enclosed in quotes. They can store text data.
Example: ["apple", "banana", "cherry"]
Lists can contain multiple strings, which is useful for storing collections of words or sentences.
3. Boolean (bool)
-----------------
Boolean values represent True or False conditions.
Example: [True, False, True]
They are often used for flags or condition checks.
4. NoneType
-----------
NoneType represents the absence of a value.
Example: [None, "value", None]
It is commonly used as a placeholder or to indicate 'no data'.
5. Mixed Data Types
-------------------
Lists can contain different types of data in the same collection.
Example: [1, "hello", 3.14, True, None]
This flexibility is one of the strengths of Python lists.
6. Nested Lists
---------------
A list can contain other lists, allowing the creation of multi-dimensional structures.
Example: [[1, 2], ["a", "b"], [True, False]]
Nested lists are often used to represent matrices or grids.
7. Tuples
---------
A tuple is similar to a list but is immutable (cannot be changed).
Example: [(1, 2), (3, 4)]
Storing tuples inside a list allows for structured data that should not be modified.
8. Sets
-------
Sets are unordered collections of unique elements.
Example: [{1, 2}, {3, 4}]
They are useful for operations involving uniqueness or mathematical set operations.
9. Dictionaries
---------------
Dictionaries store key-value pairs.
Example: [{"name": "Babin"}, {"age": 25}]
Lists of dictionaries are commonly used to represent structured records.
10. Custom Objects
------------------
You can store instances of user-defined classes in a list.
Example:
class Person:
def __init__(self, name):
self.name = name
people = [Person("Babin"), Person("Alex")]
This is helpful for object-oriented programming where you work with multiple instances.
Summary
-------
A Python list is highly flexible and can store virtually any type of object. This versatility makes it one
of the most powerful data structures in Python.