What are the various ways of creating a list?

There are several ways to create a list in Python:

  • Using square brackets: [ ] Example: my_list = [1, 2, 3, 4]
  • Using the list() constructor: Example: my_list = list([1, 2, 3, 4])
  • Using list comprehension: Example: my_list = [x for x in range(1, 5)]
  • Creating an empty list and adding elements using the append() method: Example:
my_list = []
my_list.append(1)
my_list.append(2)
my_list.append(3)
my_list.append(4)

 


Comments

Leave a Reply

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