Python list can save several elements for processing. In this tutorial, we will discuss how to create a python list variable to save data.
Create an empty list
We often need to create an empty list to start to save elements. For example, if you plan to extract some urls from a web page, you should create an empty list first.
To create an empty list, we can do like this:
urls = []
This is the simplest way, you also can do like this:
urls = list()
Create a python list with same elements
We also can create a python list which has contained some elements, for example:
urls = ['https://www.tutorialexample.com']
You will find this urls list contains an element.
Convert other object to a python list
We also can convert other object to create a python list, which may be a common process in programming.
For example, you may have got a numpy array, you can convert it to python list.
Here is an example:
import numpy as np data = np.array([1, 2, 3]) print(type(data)) data_list = data.tolist() print(type(data_list)) print(data_list)
Run this code, you will find the result:
<class 'numpy.ndarray'> <class 'list'> [1, 2, 3]
where data variable is numpy.ndarray, we can convert it to a python list data_list.
Of course, we also can convert other objects, such as pandas dataframe, python tuple to a python list.