Data Structures

Lists

In Python, a list is one of the many built-in data structures that allows us to work with a collection of data in sequential order.

  • A list begins and ends with square brackets [ and ].

  • Each item is separated by a comma , .

  • Python lists are zero-indexed.

  • Lists can contain multiple data types.

  • Lists can be 2 dimensional.

  • Lists are mutable (they can be modified in various ways using lists methods, unlike tuples )

In python, a list can contain multiple data types (unlike c or c++). List can even be defined empty and fill in later. A list can contain another list. In this way, 2D lists can be created in python.

Lists Methods

In Python, for any specific data-type there is built-in functionality that can be used to create, manipulate, and even delete data. This built-in functionality a method. Some of the methods that can be used with lists are:

  • append

  • remove (removes by elements' value)

  • add

  • insert

  • pop (removes by elements' index)

  • count

  • sort

  • Add elements to a list by index using the .insert() method.

  • Remove elements from a list by index using the .pop() method.

  • Generate a list using the range() function.

  • Get the length of a list using the len() function.

  • Select portions of a list using slicing syntax.

  • Count the number of times that an element appears in a list using the .count() method.

  • Sort a list of items using either the .sort() method or sorted() function.

When sorting a two-dimensional list using .sort(), the list by default will be sorted by the first element in each sublist. In this case, this will mean it is sorted by the price.

Two lists can simply add together. like this:

To remove an element from a 2D list:

How to append to a 2D list in Python

Accessing List Elements

A single element from a list can be accessed by using square brackets [] and the index of a the list item.

For a 2D list:

If a float is used, it will rise an error. This can be especially tricky when using division. For example print(list[4/2]) will result in an error, because 4/2 gets evaluated to the float 2.0. To solve this problem, the int() function can be used, for example: list[int(4/2)].

Modifying List Elements

A list element can be modified by calling it with its index. For example:

For a 2D list:

Tuples

tuples are created with (

tuples are immutable. use tuple when we want our data to keep the same values and formats and prevent it from changing.

to make a one element tuple, a trailing comma should be used:

Last updated