Create lists

In Python, there are multiple ways to create lists, depending on the use case. Below are the most common methods:


1. Direct Initialization (Using Square Brackets [])

The simplest way to create a list is by enclosing elements in square brackets [].

Example:

python

empty_list = []  
numbers = [1, 2, 3, 4]  
mixed_list = [1, "hello", 3.14, [5, 6]]  

2. Using the list() Constructor

The list() function can convert other iterables (like tuples, strings, sets, etc.) into a list.

Examples:

python

from_tuple = list((1, 2, 3))       # Output: [1, 2, 3]  
from_string = list("hello")         # Output: ['h', 'e', 'l', 'l', 'o']  
from_range = list(range(5))         # Output: [0, 1, 2, 3, 4]  
from_set = list({1, 2, 3})          # Output: [1, 2, 3]  

3. List Comprehension (Compact & Efficient)

List comprehensions provide a concise way to create lists based on existing iterables.

Syntax:

python

new_list = [expression for item in iterable if condition]

Examples:

python

squares = [x ** 2 for x in range(5)]            # [0, 1, 4, 9, 16]  
even_numbers = [x for x in range(10) if x % 2 == 0]  # [0, 2, 4, 6, 8]  
nested_list = [[i, j] for i in range(2) for j in range(2)]  # [[0,0], [0,1], [1,0], [1,1]]  

4. Using * Operator (Repetition)

Creates a list by repeating elements a specified number of times.

Example:

python

repeated_list = [0] * 5  # [0, 0, 0, 0, 0]  
words = ["hello"] * 3     # ["hello", "hello", "hello"]  

⚠ Caution: When used with mutable objects (like nested lists), all elements refer to the same object:

python

matrix = [[0] * 3] * 3  # [[0, 0, 0], [0, 0, 0], [0, 0, 0]]  
matrix[0][0] = 1        # [[1, 0, 0], [1, 0, 0], [1, 0, 0]] (all sublists change!)

✅ Better way (using list comprehension):

python

matrix = [[0] * 3 for _ in range(3)]  # Correctly creates independent rows  

5. Using append() or extend() (Dynamic Building)

Lists can be built incrementally using:

  • append() → Adds a single element.
  • extend() → Adds multiple elements from an iterable.

Examples:

python

lst = []  
lst.append(1)           # [1]  
lst.extend([2, 3, 4])   # [1, 2, 3, 4]  
lst.append([5, 6])      # [1, 2, 3, 4, [5, 6]]  

6. Using split() (From Strings)

The split() method breaks a string into a list based on a delimiter.

Example:

python

sentence = "Python is awesome"  
words = sentence.split()  # ['Python', 'is', 'awesome']  

csv_data = "1,2,3,4"  
numbers = csv_data.split(',')  # ['1', '2', '3', '4']  

7. Using map() (Apply Function to Elements)

Converts an iterable into a list after applying a function.

Example:

python

str_numbers = ["1", "2", "3"]  
int_numbers = list(map(int, str_numbers))  # [1, 2, 3]  

8. Using copy() or Slicing (Clone a List)

Creates a shallow copy of an existing list.

Examples:

python

original = [1, 2, 3]  
copy1 = original.copy()      # [1, 2, 3]  
copy2 = original[:]          # [1, 2, 3] (slicing)  

⚠ Note: For nested lists, use copy.deepcopy() to avoid shared references.


9. Using + Operator (Concatenation)

Combines two or more lists into a new one.

Example:

python

list1 = [1, 2]  
list2 = [3, 4]  
combined = list1 + list2  # [1, 2, 3, 4]  

10. Using *args (Unpacking Iterables)

Unpacks elements from other iterables into a new list.

Example:

python

numbers = [*range(3), *[4, 5]]  # [0, 1, 2, 4, 5]  

Summary Table

MethodExampleUse Case
Direct Initialization[1, 2, 3]Simple list creation
list() Constructorlist("hello")Convert iterables to lists
List Comprehension[x**2 for x in range(5)]Efficient transformations/filtering
* Operator[0] * 5Repeat elements
append()/extend()lst.append(1)Dynamic list building
split()"a b c".split()Convert strings to lists
map()list(map(int, ["1","2"]))Apply a function to elements
copy()/Slicingnew = old.copy()Clone a list
+ Operator[1,2] + [3,4]Concatenate lists
Unpacking (*args)[*[1,2], *[3,4]]Merge iterables

Similar Posts

  • Random Module?

    What is the Random Module? The random module in Python is used to generate pseudo-random numbers. It’s perfect for: Random Module Methods with Examples 1. random() – Random float between 0.0 and 1.0 Generates a random floating-point number between 0.0 (inclusive) and 1.0 (exclusive). python import random # Example 1: Basic random float print(random.random()) # Output: 0.5488135079477204 # Example…

  • Built-in Object & Attribute Functions in python

    1. type() Description: Returns the type of an object. python # 1. Basic types print(type(5)) # <class ‘int’> print(type(3.14)) # <class ‘float’> print(type(“hello”)) # <class ‘str’> print(type(True)) # <class ‘bool’> # 2. Collection types print(type([1, 2, 3])) # <class ‘list’> print(type((1, 2, 3))) # <class ‘tuple’> print(type({1, 2, 3})) # <class ‘set’> print(type({“a”: 1})) # <class…

  • Indexing and Slicing in Python Lists Read

    Indexing and Slicing in Python Lists Read Indexing and slicing are fundamental operations to access and extract elements from a list in Python. 1. Indexing (Accessing Single Elements) Example 1: Basic Indexing python fruits = [“apple”, “banana”, “cherry”, “date”, “fig”] # Positive indexing print(fruits[0]) # “apple” (1st element) print(fruits[2]) # “cherry” (3rd element) # Negative indexing print(fruits[-1]) # “fig”…

  • Alternation and Grouping

    Complete List of Alternation and Grouping in Python Regular Expressions Grouping Constructs Capturing Groups Pattern Description Example (…) Capturing group (abc) (?P<name>…) Named capturing group (?P<word>\w+) \1, \2, etc. Backreferences to groups (a)\1 matches “aa” (?P=name) Named backreference (?P<word>\w+) (?P=word) Non-Capturing Groups Pattern Description Example (?:…) Non-capturing group (?:abc)+ (?i:…) Case-insensitive group (?i:hello) (?s:…) DOTALL group (. matches…

  • Classes and Objects in Python

    Classes and Objects in Python What are Classes and Objects? In Python, classes and objects are fundamental concepts of object-oriented programming (OOP). Real-world Analogy Think of a class as a “cookie cutter” and objects as the “cookies” made from it. The cookie cutter defines the shape, and each cookie is an instance of that shape. 1. Using type() function The type() function returns…

  • Variable Length Keyword Arguments in Python

    Variable Length Keyword Arguments in Python Variable length keyword arguments allow a function to accept any number of keyword arguments. This is done using the **kwargs syntax. Syntax python def function_name(**kwargs): # function body # kwargs becomes a dictionary containing all keyword arguments Simple Examples Example 1: Basic **kwargs python def print_info(**kwargs): print(“Information received:”, kwargs) print(“Type of…

Leave a Reply

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