Python Lists Explained: Objects, Data Types, and Nested Lists with Examples

A List Can Contain Integer Objects

A list can contain integer objects.

numbers = [10, 20, 30, 40, 50]

print(numbers)

Output:

[10, 20, 30, 40, 50]

The list contains five integer objects.

A List Can Contain Float Objects

A list can also contain floating-point numbers.

temperatures = [25.5, 26.2, 27.8, 28.1, 29.4]

print(temperatures)

Output:

[25.5, 26.2, 27.8, 28.1, 29.4]

A List Can Contain String Objects

A list can contain strings.

names = ["Ram", "John", "Ali", "Ravi", "David"]

print(names)

Output:

[‘Ram’, ‘John’, ‘Ali’, ‘Ravi’, ‘David’]

Each name is a separate string object in the list.

A List Can Contain Boolean Objects

Lists can also contain Boolean objects.

values = [True, False, True, True, False]

print(values)

Output:

[True, False, True, True, False]

The two Boolean values available in Python are:

True
False

A List Can Contain Different Types of Objects

One of the useful features of Python lists is that a single list can contain objects of different types.

For example:

data = [
  10,
  3.14,
  "Python",
  True,
  25
]

print(data)

Output:

[ 10, 3.14, ‘Python’, True, 25 ]

Here the list contains:

10 integer object
3.14 float object
“Python” string object
True Boolean object
25 integer object
Such a list is called a heterogeneous list because it contains objects of different types.

A List Can Even Contain Other Lists

A list can contain another list as one of its objects.

For example:

numbers = [
  [10, 20],
  [30, 40],
  [50, 60]
]

print(numbers)

Output:

[ [10, 20], [30, 40], [50, 60] ]

Here, the outer list contains three list objects.

Important: This concept is useful when representing data in rows and columns.

For example:

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

print(matrix)

Output:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

We will study such nested lists separately.

Final Understanding

The most important thing to understand about a Python list is:

A list is an ordered, mutable collection of objects. Mutable means, we can change value of an object.

For example:

data = [10, 3.14, "Python", True]

The list contains four objects:

10 integer object
3.14 float object
“Python” string object
True Boolean object
Important: The list itself is also an object.
Remember: A Python list stores references to objects, and those objects can be of different types.

Gopal Krishna

Hey Engineers, welcome to the award-winning blog,Engineers Tutor. I'm Gopal Krishna. a professional engineer & blogger from Andhra Pradesh, India. Notes and Video Materials for Engineering in Electronics, Communications and Computer Science subjects are added. "A blog to support Electronics, Electrical communication and computer students".

Leave a Reply

Your email address will not be published. Required fields are marked *

Translate »