How do I create a Python list?

Python3’s basic data type inside a very important ordered collection of objects, it is a list (List), support in place to modify, can contain any kind of other objects, even the list itself, this article we will look at the python list creation method and considerations.

Create a list directly with bracket assignment

Python lists are represented in the source code by English half-angle brackets [ ], for example.

>>> lis = [ ]

The code means assigning an empty list (that is, the empty brackets) to the variable lis, so that we create a list named lis, which is one of the ways to create a list, and then we will look at other ways to create a list and their advantages and disadvantages.

Create a list with the Python3 built-in function list

>>>lis2 = list()  # This creates an empty list
>>>lis2 = list('')
['w', 'w', 'w', '.', '7', 'i', 'x', '.', 'n', 'e', 't']

The above code can be based on the function filled in the string (‘’) to create a list containing each element, which is equivalent to breaking up the string into a list, the same Python there are ways to combine the list as a string, next time we will talk about.

These two methods of creating lists are more commonly used, and both have their uses. The first one directly contains any data type when created, including itself (that is, the nested list list data type), and the second one can convert other data types to list types, such as tuple tuples and dictionary dict, string str to list.

Let’s take an example below.

>>> lis = [123, 'abc', True, {'site': ''}, (3.14, 2020)]
>>> # Lists containing multiple data types
>>> lis2 = [123, ['abc', 111, 222], 'list']
>>> # Nested lists created

Other methods can also be used to quickly create python lists, range(), list derivatives, etc., which are more advanced knowledge for newbies and will not be expanded in this article.

Leave a Reply