Python Crash Course
)}

List Data Types

In this lesson we're going to introduce List data types.

The most basic data structure in Python is the sequence.

L‍ists are always written in square brackets [ ] , and each element of a list is seperated by a comma , . If I want to declare a list of names, I would simply need to write:

names = ["John", "Jane", "Joe"]

"John" would have an index of 0. "Jane" would have an index of 1. "Joe" would have an index of 2.

Accessing elements based on the index

let's say I want to access the element at index 0:

print(names[0])

>‍> John

As expected the output of names at index 0 is "John"

let's change the index to 2:

print(names[2])

>> Jane

Since we're able to access based on the index, we can claim that this list is Ordered.

A list holds elements and all these elements are separated by commas such that an element is accessed according to its index.‍

A‍ccessing an index beyond the range of elements

Since this is an ordered list, if you try to access an index that's beyond the range of your list, you will get an error. For example, lets try accessing the index 100 of names:

print(names[100])

>> IndexError: list index out of range

The output is the error thrown by Python when you try to access an index beyond the range of elements in your list.

Lists can hold a mix of data types

Now it's important to note that lists don't have to contain a single data type. It can contain all of strings, floats, integers and booleans at the same time. For example:

random_variable = [ True , False , 'Hello' , 0 , 1.2 ]

H‍ow to get the length of a List?

Just like strings you can also get the length of a list using the len function.

print(len(random_variable))

>> 5

G‍etting the last element of a List

There are a few ways to get the last element of List.

  • using **len**
random_variable = [ True , False , 'Hello' , 0 , 1.2 ] length = len(random_variable) print(length) final_element = random_variable[length] print(final_element)

>> 5

‍>> IndexError: list index out of range

This produces an error because the value of length is 5. However the maximum index of random_variable is 4 since we start counting indices of a List from 0.

Therefore, in order to make this work we need to to subtract 1 from the length:

random_variable = [ True , False , 'Hello' , 0 , 1.2 ] length = len(random_variable) print(length) final_element = random_variable[length - 1] print(final_element)

‍>> 5

>> 1.2

Using negative values

A‍lternatively, you can access the final elements of a list using negative numbers, for example:

random_variable = [ True , False , 'Hello' , 0 , 1.2 ] print(random_variable[-1])

‍>> 1.2

‍You can also go further down the list:

print(random_variable[-2]) print(random_variable[-3])

‍>> 0

>> Hello

Feedback Summary
4.8
8 students
5

75%
4

25%
3

0%
2

0%
1

0%
Written Reviews
There are no written reviews yet.