Python Tutorial - List Introduction

Python Exercise Lists

In actual development, it is often necessary to store a set (more than one) of data for later code use. Having said that, some readers may have heard of Array, which can store multiple data one by one, and each element in the array can be accessed through the array index

To be clear, there are no arrays in Python, but more powerful lists have been added. If you think of an array as a container, then a Python list is a factory repository.

Formally, the list will enclose all elements in a pair of square brackets [], with adjacent elements separated by commas, as shown below:

[element1, element2, element3, ..., elementn]

In the format, element1 ~ elementn represent the elements in the list, there is no limit to the number, as long as it is a data type supported by Python.

In terms of content, lists can store any type of data such as integers, decimals, strings, lists, and tuples, and the types of elements in the same list can also be different. For example:

["", [7, 8, 9], 8.8]

As you can see, the list contains data types such as string, integer, list, and floating point.

Note that when using lists, although different types of data can be put into the same list, usually it is not advisable. Because only the same type of data is put into the same list, which can improve the readability of the program.

In addition, in other Python tutorials, list is often used to refer to a list, because the data type of a list is a list, which can be known through the type () function, for example:

type( ["", [7, 8, 9], 8.8])

The output is:


As you can see, its data type is list, which means it is a list.

Python List Creator

There are two ways to create lists in Python, which are described below.

1) Use [] to create a list directly

After using [] to create a list, generally use = to assign it to a variable, the specific format is as follows:

listname = [element1, element2, element3, ..., elementn]

Among them, listname represents the variable name, whileas element1 ~ elementn represent the list elements.

For example, the lists defined below are all legal:

num = [5, 6, 7, 8, 9]
name = ["Python Website", ""]
program = ["C language", "Python", "Java"]

In addition, when creating a list in this way, there can be multiple or none of the elements in the list, for example:

emptylist = []

This shows that emptylist is an empty list.

2) Create a list using the list () function

In addition to using [] to create lists, Python provides a built-in function list(), which can be used to convert other data types to list types. Example:

#Convert strings to lists
list1 = list("python")
#Convert tuples into lists
tuple1 = ('Python', 'Java', 'C ++', 'JavaScript')
list2 = list (tuple1)
print (list2)
#Convert dictionary to list
dict1 = {'a': 130, 'b': 32, 'c': 8}
list3 = list (dict1)
print (list3)
#Convert interval to list
range1 = range (3, 8)
list4 = list (range1)
print (list4)
#Create empty list
print (list ())

The output is:

['p', 'y', 't', 'h', 'o', 'n']
['Python', 'Java', 'C ++', 'Javascript']
['a', 'b', 'c']
[3, 4, 5, 6, 7]

Python Access List Element

A list is a type of Python sequence. We can use an index to access an element in the list (getting the value of an element), or we can use a slice to access a set of elements in the list (getting a new Sublist).

The format for accessing list elements using an index is:

listname [i]

Among them, listname represents the name of the list, and i represents the index value. The index of the list can be positive or negative.

The format for accessing list elements using slices is:

listname [start: end: step]

Among them, listname represents the name of the list, start represents the starting index, end represents the ending index, and step represents the step size.

The above two methods have been explained in the "Python sequence", so I won't repeat them here, just for example demonstration, please see the following code:

url = list ("")
#Access an element in a list using an index
print (url [8]) #Use positive index
print (url [-9]) #Use negative index
#Access a set of elements in a list using a slice
print (url [2: 18]) #Use positive slice
print (url [2: 18: 3]) #Specify the step size
print (url [-9: -1]) #Use negative slice

The output is:

['w', '.', 'f', 'r', 'e', 'e', 'l', 'e', 'a', 'r', 'n', 'i', 'n', 'g', 'p', 'o']
['w', 'r', 'l', 'r', 'n', 'o']
['o', 'i', 'n', 't', 's', '.', 'c', 'o']

Python Delete List

For the list that has been created, if it is no longer used, you can delete it using the del keyword.

In actual development, del is not often used to delete lists, because Python's built-in garbage collection mechanism will automatically destroy useless lists. Even if the developer does not delete them manually, Python will automatically recycle them.

The syntax of the del keyword is:

del listname

Where listname is the name of the list to delete.

[Example] Python delete list:

list_1 = [""]
del list_1

The output is:

NameError          Traceback (most recent call last)
[ipython-input-54-a17d8657c9d0] in [module]
2 print(list_1)
3 del list_1
----> 4 print(list_1)
NameError: name 'list_1' is not defined


More Tutorials:

Python Installation - Linux (Ubuntu)
Python Installation - Mac OS
Integrated Development Environment - IDE
Python - Basic Variables
Python - Sequence Introduction
Python - Output Formatting
Python - Escape Character
Python - Type Conversion
Python - Numbers
Python – Arithmetic Operators
Python – Assignment Operators
Python – Comparison Operators
Python – Logical Operators
Python – Precedence and Associativity Operators
Python – Bytes Type and Usage
Python – Long & Raw Strings
Python – Concatenate Function
Python – Slice Function
Python – Length and Split Function
Python – Join and Count Function
Python – Find Function
Python – Index Function
Python – Alignment Function
Python – Startswith and Endswith Function
Python – String Case Conversion
Python – Remove Specified Character
Python – Encode and Decode Function
Python – dir and help Function
Python – Input Output Introduction
Python – Basic Operation
Python – Open Function
Python – Read Function
Python – Readline Function
Python – Write Function
Python – Close Function
Python – Seek and Tell Function
Python – Pickle Module
Python - File Input Module and Linecache Module
Python - Pathlib Module
Python - Pathlib Module
Python - os.path Module
Python - fnmatch Module
Python - Tuple Introduction
Python - List Introduction
Python - List Add Element
Python - List Delete Element
Python - List Modification Element
Python - List Find Element
Python - Dictionary Introduction
Python - Dictionary Basic Operation
Python - Dictionary Method Guide
Python - Set Collection
Python - Set Basic Operation
Python - Set Basic Method
Python - Frozenset Method
Python - If Condition I
Python - If Condition II
Python - While loop
Python - For loop
Python - Pass Statement
Python - Break Statement
Python - Zip Reverse Function
Python - Function Introduction
Python - Positional Parameters
Python - Key Arguments
Python - None and Return
Python - Variable Scope
Python - Local Function
Python - Closure Method
Python - Lamdba Expression

More Python Exercises:

Python String Exercises
Python List Exercises
Python Library Exercises
Python Sets Exercises
Python Array Exercises
Python Condition Statement Exercises