Creating a List in Python
First of all, Let’s have a look at how we can create a list in python. Basically, there are multiple ways with which we can create a list, and we are going to explore some different ways here. We will have a look at two ways to create lists, with the help of the square brackets, and also by using the list function (list constructor). Let’s have a look at both the ways now, and also, we would check the type of the object, with the type function. Have a look at the below programs, which demonstrate the creation of list.
Creating a List in Python
As you can see, we have created a reference variable my_list, and we have made use of the square brackets, to create a list.
After that, we are also checking the type of the object, using the type function. The output of the above program comes out to be something like this –
<class ‘list’>
As you can see, the object is of the class list. The thing is that this list that we have created is an empty list. But here, we can also have some elements, like this –
As you can see, in the square brackets, we have some elements now, separated with comma, and those are the elements of the list. After that, we are also printing the list. Just writing the reference variable of the list here, can help you print the list. The output of the above program looks something like this –
[1, 2, 3, 4, 5]
As you can see, we got the list, with the specified elements. The thing is that in the list, we can have some data of different data types as well. But before we move towards that, Let’s have a look at how we can create a list, using the list constructor.
As you can see, we have used the constructor here, to create a list in our program. After that, we are also printing the type of the object, which is again going to say that the object belongs to the class list, but let’s have a look at the output of the above program once.
<class ‘list’>
As you can see again, we have created the list, using the list constructor. In the above program, since we are not giving any argument to the constructor, we are creating the empty list. Also, when we would give some argument, it has to be some iterable.
So, here, we have seen some different ways using which, we can simply create list in our python programs. One way was using the square brackets, and the other was using the list constructor. Later on, as we move forward, we are going to explore the concept of list, and we are going to explore much about the list, like adding elements, accessing them, and a bunch of different methods as well, which help us do some different things with our list.