Python

Lists

A list is a collection of objects

Everything in Python is an object. These objects in a list are numbers in most cases. Lists can also contain text (strings) or both.

Note: Lists can have zero or more elements (empty lists are possible).

Related Course: Complete Python Bootcamp: Go from zero to hero in Python

Lists Example

A list is defined using square brackets. Let us define as simple list:

c = [5,2,10,48,32,16,49,10,11,32,64,55,34,45,41,23,26,27,72,18]

In this case we have a list defined by the variable c. We defined a purely random set of numbers above.

Accessing elements

To access individual elements, we use the same brackets. To print the first element (Python starts counting from zero):

print(c[0])

This shows

5

To print the second element:

print(c[1])

Results in:

2

To print the last element, you can count from the back using the minus sign.

print(c[-1])

Result

18

Size of the list

You can get the length of the list using the len function. Example code:

c = [5,2,10,48,32,16,49,10,11,32,64,55,34,45,41,23,26,27,72,18]
print(len(c))

Datatypes

List may contain various types of variables in the same list including text, whole numbers, floating point numbers and so on. For example, we may define a list with text variables:

fears = ["Spiders","Ghosts","Dracula"]

Previous Post Next Post

Cookie policy | Privacy policy | ©