List Creation Python

List Creation and Initialization in Python Code

In Python, there are multiple ways to create and initialize lists. Here are some common methods:

Creating an Empty List

Python Code

# Method 1: Using square brackets

empty_list = []

# Method 2: Using the list() function

empty_list = list()

Creating and Initializing a List with Values

Python Code

# Method 1: Using square brackets

fruits = ["apple", "banana", "cherry"]

# Method 2: Using the list() function with a sequence

fruits = list(["apple", "banana", "cherry"])

Creating a List with Repeated Values

Python Code

# Method 1: Using multiplication

zeros = [0] * 5 # [0, 0, 0, 0, 0]

# Method 2: Using list comprehension

zeros = [0 for _ in range(5)] # [0, 0, 0, 0, 0]

Creating a List Using List Comprehension

List comprehensions provide a concise way to create lists.

Python Code

# Method 1: Basic comprehension

squares = [x**2 for x in range(10)] # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# Method 2: With a condition

even_squares = [x**2 for x in range(10) if x % 2 == 0] # [0, 4, 16, 36, 64]

Initializing a List with Default Values

You can initialize a list with default values using list comprehension or the * operator.

Python Code

# Method 1: Using the * operator

default_values = [1] * 5 # [1, 1, 1, 1, 1]

# Method 2: Using list comprehension

default_values = [1 for _ in range(5)] # [1, 1, 1, 1, 1]

Creating a List from an Existing Iterable

You can create a list from any iterable, such as a string, tuple, or set.

Python Code

# From a string

chars = list("hello") # ['h', 'e', 'l', 'l', 'o']

# From a tuple

numbers_tuple = (1, 2, 3)

numbers_list = list(numbers_tuple) # [1, 2, 3]

# From a set

numbers_set = {1, 2, 3}

numbers_list = list(numbers_set) # [1, 2, 3]

Creating Nested Lists

You can create lists of lists to represent matrices or more complex data structures.

Python Code

# Method 1: Using nested lists

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

# Method 2: Using list comprehension for a 2D array

matrix = [[0 for _ in range(3)] for _ in range(3)] # 3x3 matrix filled with zeros

These methods cover a wide range of scenarios for list creation and initialization in Python.

Top of Form

Post a Comment

Previous Post Next Post