Python Create List

Python Create List

In Python, you can create a list using the double square brackets. While doing so, you do not have to put any element inside it.

Example

Python Create List example1

When you are creating a list, you can add any number and any type of elements in that list. You just have to separate those values by a “comma”.

Example

Python Create List example 2

Creating a Python list of size n

Python doesn’t allow you to create a list constrained by a size limit unlike other programming languages. However, while creating a list, you can determine the initial size of the list.

It would make more sense after going through the example below:

Example

Python Create List example 3

Our list in the example holds ten None values. This is different from an empty list because assigning an element to an index in the empty list would result in an error.

Example

Python Create List example 4

Having None values is more than having no values at all. You can always add more values to it. But there is a more generic and “Pythonic” way to create a list with initial size.

The way is to use a for loop over the range of n. Let’s check the below example.

Example

Python Create List example 5

Python create list of Objects

You can append instances of classes into a list. Each index of the list is associated with the instance attributes and the methods of class.

The methods can be accessed when you add them in the way shown below.

Example

Python Create List example 6

The object references get stored in our list. If you know C language, you might have noticed that the list in the example above is behaving like an array structure.

Tutorials for all brains!