What a list is

A list is a mutable data type, which means you can change the contents of a list without creating a new list. The elements of a list can be of different data types. A single list can contain numbers, strings, other lists, tuples—and even functions and classes.

In Python, a list literal (the actual data, not a name referring to the data) is defined by square brackets surrounding zero or more elements. Elements are separated by commas. Below are examples of lists:

a_list = ['this', 'is', 'a', 'list'] empty list = [] another list = [5]

Lists come with a variety of built-in methods that let you manipulate them. For example, to sort a list, you write code like this:

>>> mylist = [8, 33, 29, 4, 1, 5, 98] >>> mylist.sort() >>> mylist

Was this article helpful?

0 0

Post a comment