How to Use Python Lists: Same vs. Multiple Data Types

Understanding Python Lists

A fundamental, versatile, and built-in data structure used to store collections of items.

What is a List?

In Python, a List is an ordered, mutable (changeable) collection of elements. Lists are written with square brackets [], and items inside them are separated by commas.

Ordered Mutable (Modifiable) Allows Duplicates Indexed (Starts at 0)

Types of Lists by Data Content

Python lists are highly flexible because they do not restrict what kinds of data you put inside them.

1. List with Same Data Types (Homogeneous)

This is the most common use case, where all elements share the identical data type (e.g., all integers, all strings).

# A list of integersnumbers = [10, 20, 30, 40]# A list of stringsfruits = ["apple", "banana", "cherry"]print(numbers[1])# Output: 20

2. List with Multiple Data Types (Heterogeneous)

Python dynamic typing allows you to mix different data types—integers, strings, floats, and even booleans—in a single list.

# Mixed data types in one listmixed_list = ["John", 25, True, 98.6]# Printing the entire listprint(mixed_list)# Output: ["John", 25, True, 98.6]

3. Nested Lists (Lists inside a List)

A list can also contain other lists as elements. This is often used to represent matrices or multi-dimensional data structures.

# A 2D matrix listmatrix = [ [1, 2, 3], [4, 5, 6]]print(matrix[0][1])# Output: 2

4. Empty List

An empty list contains no elements initially. It is frequently initialized to dynamically accumulate items later in the program execution.

# Initializing an empty listdynamic_data = []# Adding data laterdynamic_data.append("First Item")

Core List Operations

Here is a quick snapshot of how you modify and interact with lists in Python:

# 1. Creationmy_list = ["Python", "Java"]# 2. Adding items (Append adds to the end)my_list.append("C++")# 3. Changing an item (Mutability)my_list[1] = "Kotlin"# 4. Checking the sizelength = len(my_list)print(my_list)# Final Output: ["Python", "Kotlin", "C++"]

Comments