The list is the primary container (data structure) used to store in-memory data in a Python program. In this article I’m going to describe how lists are used in Python and also demonstrate many of the built-in methods you can use to work with lists. I’ll also look at some Python functions that take lists as arguments and one or two keywords (in and not in) that can be used with lists as well.

Python Lists Defined and Demonstrated

A list is a sequential collection of data stored under a single name. The Python list is comparable to arrays and vectors in other languages. One feature of Python lists that stands out from similar containers in other languages is that Python lists can store multiple types of data in the same list.

A list is created by assigning a set of empty brackets to a variable. Here is the syntax template for creating a new list:

_list-name = []_

Here is an example of a code fragment that creates a new list:

numbers = []

You can also create a new list with data already in it, as in this example:

names = [“Cynthia”, “Jonathan”, “Raymond”, “Danny”]

The elements of the list are said to be stored by their index position. The beginning index position of a list is always 0, followed by 1, 2, 3, and so on. In the names list created above, “Cynthia” is at position 0, “Jonathan” is at position 1, “Raymond” is at position 2, and “Danny” is at position 3.

**Data is added to a list using the **append method. Here is the syntax template for the append method:

list-name.append(value)

The following code fragment stores the numbers 1 through 10 in the list created just above:

for i in range(1, 11):
  numbers.append(i)

Unlike other languages, you can print the values stored in a list just by calling the print function with the list name, as in this line of code:

print(numbers)

which displays this using the code I’ve already written:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

If you need to insert data into an existing list, you can do that using the insert method. Here is the syntax template for this method:

list-name.insert(index-position, value)

**Here is a complete program that demonstrates how to use the **insert method:

numbers = [1,3,5]
print(numbers)
numbers.insert(1,2)
print(numbers)
numbers.insert(3,4)
print(numbers)

#python-example #python-programming #python #machine-learning

Learning Python: Lists and List Methods (and Functions)
1.65 GEEK