Skip to content
Home » List Basics in Python

List Basics in Python

Spread the love

Today we’ll be talking about the very basics of lists.

Here’s the video version of this article:

A list is an ordered collection of elements.

Lists can contain numbers, strings or other arbitrary types of data. We define lists with square brackets. Lists are ordered. We access list elements via square brackets:

>>> names = ["Alice", "Bernard", "Steve", "Emma", "Sam"]  # a list of strings

>>> numbers = [3, 7, 12, 1, -54, 8]     # a list of ints

>>> names[0]
'Alice'

>>> numbers[1] + numbers[5]     # so 7 + 8 = 15
15

Lists are mutable. You can change any element:

>>> cars = ["Mercedes", "Ford", "BMW", "Toyota"]
>>> cars[2] = "Porsche"
>>> cars
['Mercedes', 'Ford', 'Porsche', 'Toyota']

A list may contain elements of different types. It may also contain lists:

['yes', 13.75, [1, 2, 'abc'], 2, True, 'x']

Membership

We can check if an element is contained or not in a list using the in and not in membership operators:

>>> rivers = ["Orinoco", "Potomac", "Nile"]

>>> "Thames" in rivers
False

>>> "Snake River" not in rivers
True

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love
Tags:

Leave a Reply