Skip to content

[Python] Lists Tutorial (With Examples)

Last Updated on 2021-10-11 by Clay

List is a most basic data structure in Python, every element can be a value, string or boolean. Every element has its index, counting from 0.

Today I want to record how to operate List in Python. I will introduce it into the following subsections:

  • Initialize a List
  • Access the elements of List
  • Update the elements of List
  • Delete the elements of List
  • Common methods of operation in List

Initialize a List

If we want to create a List, we can use list() or [] to built it; If you want to initialize the elements in the List, you can directly fill them in square brackets.

It is worth noting that not all the elements of List in Python have the same data type.

Such as the following sample code, you can put both integers and strings at the same time.

Each element needs to be separated by a comma ,.

List_1 = list()
List_2 = []
List_3 = [1, 2, "hello"]

print("List_1:", List_1)
print("List_2:", List_2)
print("List_3:", List_3)


Output:

List_1: []
List_2: []
List_3: [1, 2, 'hello']



Access the elements of List

If you want to print out the elements in the List, you can use for to get the element value; but in addition, you can also use index to print out the corresponding elements one by one.

In Python, if there is no judgment related to the index, it is recommended to obtain the element value directly, the execution efficiency of the program is better.

List = [1, 2, "hello"]


# Method 1
for element in List:
    print(element)


# Method 2
for i in range(len(List)):
    print(List[i])


Output:

1
2
hello
1
2
hello


As you can see, both of two ways can print all elements of List.


After learning how to print out elements, let's take a look at other access techniques for List in Python.

  • If the index value out of List length, you will get an error message about: IndexError: list index out of range
  • You can use a negative index, which will access the element of the List from the end
  • : is a symbol for traversing all element values. If you use n:m to access the List, then you will get from the element at index n to the element at index m-1
List = [1, 2, "hello"]

print("List:", List)
print("List[-1]:", List[-1])
print("List[1:]:", List[1:])
print("List[-2:]:", List[-2:])
print("List[3]:", List[3])


Output:

List: [1, 2, 'hello']
List[-1]: hello
List[1:]: [2, 'hello']
List[-2:]: [2, 'hello']
Traceback (most recent call last):
  File "/Users/clay/Projects/PythonProjects/python_children_edu/try.py", line 7, in <module>
    print("List[3]:", List[3])
IndexError: list index out of range


There are many things that can be studied here, please feel free to try different writing methods, I believe that the use of Python List will be more handy.


Update the elements of List

To update elements of List is very easy, just need to assign a new value to the element at the specified index.

List = [1, 2, "hello"]

# Update
List[2] = 3
print(List)


Output:

[1, 2, 3]



Delete the elements of List

You can use del command to delete the elements of List.

List = [1, 2, "hello"]

# Delete
del List[0]
print(List)


Output:

[2, 'hello']



Common methods of operation in List

There are many common operation methods in List, including:

  • list.append(x): Add a new element to the end of the list
  • list.extend(iterable): Add a new iterable object to the end of the list
  • list.insert(i, x): Insert a new element at a specific index i
  • list.remove(x): Remove the element whose first item value is x in the list
  • list.pop([i]): Remove the element at the specified index in the List and return it. If no index is specified, delete the last item in the return list
  • list.clear(): Clear whole List
  • list.index(x): Return the index of first element x
  • list.count(x): Count how many elements in the list are x
  • list.sort(reverse=False): Sort the elements in the list
  • list.reverse(): Reverse the elements in the list
  • list.copy(): Return a shallow copy of the List


list.append(x)

List = [1, 2, 3]

# Append
List.append(4)
print(List)


Output:

[1, 2, 3, 4]



list.extend(iterable)

List = [1, 2, 3]
iterable = [4, 5, 6]

# Extend
List.extend(iterable)
print(List)


Output:

[1, 2, 3, 4, 5, 6]



list.insert(i, x)

List = [1, 2, 3]

# Insert
List.insert(1, 1.5)
print(List)


Output:

[1, 1.5, 2, 3]



list.remove(x)

List = [1, 2, 3]

# Remove
List.remove(2)
print(List)


Output:

[1, 3]



list.pop([i])

List = [1, 2, 3]

# Pop
List.pop()
print(List)


Output:

[1, 2]



list.clear()

List = [1, 2, 3]

# Clear
List.clear()
print(List)


Output:

[]



list.index(x)

List = [1, 2, 3]

# Index
print(List.index(3))


Output:

2



list.count(x)

List = [1, 2, 3]

# Count
print(List.count(3))


Output:

1



list.sort()

  • reverse=False: From small to large
  • reverse=True: From large to small
List = [1, 2, 3]

# Sort
List.sort(reverse=True)
print(List)


Output:

[3, 2, 1]



list.reverse()

List = [1, 2, 3]

# Reverse
List.reverse()
print(List)


Output:

[3, 2, 1]



list.copy()

If you use assign instead of list.copy(), the elements of Lists shared the same memory address; the disadvantage is that if you change the original List, the elements under the List you assign will also change.

This is a very common error in Python.

Let's take a look at an example of comparison:

List = [1, 2, 3]

# Copy
List_assign = List
List_copy = List.copy()

# Change element
List[1] = 20
print("List:", List)
print("List_assign:", List_assign)
print("List_copy:", List_copy)


Output:

List: [1, 20, 3]
List_assign: [1, 20, 3]
List_copy: [1, 2, 3]




References


Read More

Tags:

Leave a ReplyCancel reply

Exit mobile version