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

  • Formatting Date and Time in Python

    Formatting Date and Time in Python Python provides powerful formatting options for dates and times using the strftime() method and parsing using strptime() method. 1. Basic Formatting with strftime() Date Formatting python from datetime import date, datetime # Current date today = date.today() print(“Date Formatting Examples:”) print(f”Default: {today}”) print(f”YYYY-MM-DD: {today.strftime(‘%Y-%m-%d’)}”) print(f”MM/DD/YYYY: {today.strftime(‘%m/%d/%Y’)}”) print(f”DD-MM-YYYY: {today.strftime(‘%d-%m-%Y’)}”) print(f”Full month: {today.strftime(‘%B %d, %Y’)}”) print(f”Abbr…

  • Python Calendar Module

    Python Calendar Module The calendar module in Python provides functions for working with calendars, including generating calendar data for specific months or years, determining weekdays, and performing various calendar-related operations. Importing the Module python import calendar Key Methods in the Calendar Module 1. calendar.month(year, month, w=2, l=1) Returns a multiline string with a calendar for the specified month….

  • math Module

    The math module in Python is a built-in module that provides access to standard mathematical functions and constants. It’s designed for use with complex mathematical operations that aren’t natively available with Python’s basic arithmetic operators (+, -, *, /). Key Features of the math Module The math module covers a wide range of mathematical categories,…

  • Inheritance in OOP Python: Rectangle & Cuboid Example

    Rectangle Inheritance in OOP Python: Rectangle & Cuboid Example Inheritance in object-oriented programming (OOP) allows a new class (the child class) to inherit properties and methods from an existing class (the parent class). This is a powerful concept for code reusability ♻️ and establishing a logical “is-a” relationship between classes. For instance, a Cuboid is…

  • Operator Overloading

    Operator Overloading in Python with Simple Examples Operator overloading allows you to define how Python operators (like +, -, *, etc.) work with your custom classes. This makes your objects behave more like built-in types. 1. What is Operator Overloading? 2. Basic Syntax python class ClassName: def __special_method__(self, other): # Define custom behavior 3. Common Operator Overloading Methods Operator…

  • re module

    The re module is Python’s built-in module for regular expressions (regex). It provides functions and methods to work with strings using pattern matching, allowing you to search, extract, replace, and split text based on complex patterns. Key Functions in the re Module 1. Searching and Matching python import re text = “The quick brown fox jumps over the lazy dog” # re.search()…

Leave a Reply

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