Write a python program to create a simple list and nested list with different datatypes

1. Introduction

This blog post will demonstrate how to create a simple list and a nested list containing different data types in Python. Lists are versatile data structures in Python that can store elements of multiple data types, including other lists, making them ideal for various applications.

2. Program Steps

1. Create a simple list with elements of different data types.

2. Create a nested list, which is a list containing other lists, again with different data types.

3. Print both lists to show their structure and contents.

3. Code Program


def create_lists():
    # Step 1: Create a simple list with different data types
    simple_list = [1, "Python", 3.14, True]

    # Step 2: Create a nested list with different data types
    nested_list = [simple_list, [2, "Nested", 2.71], ["Another List", False]]

    # Step 3: Print the lists
    print("Simple List:", simple_list)
    print("Nested List:", nested_list)

# Call the function to create and display the lists
create_lists()

Output:

Simple List: [1, 'Python', 3.14, True]
Nested List: [[1, 'Python', 3.14, True], [2, 'Nested', 2.71], ['Another List', False]]

Explanation:

1. The function create_lists initializes simple_list with elements of various data types, including an integer, a string, a float, and a boolean.

2. It then creates nested_list, which contains simple_list as its first element, demonstrating how lists can store other lists. The other elements in nested_list include another list with an integer, a string, and a float, and another list with a string and a boolean.

3. Both lists are printed to show their structure and contents. The simple_list displays its diverse data types, while nested_list shows how lists can be nested within each other.

This program exemplifies the flexibility of lists in Python, capable of holding a wide range of data types, including other lists, making them suitable for complex data structures.


Comments