Search this site
Embedded Files
AIMD GPDS Courses
  • Home
  • Courses
  • Contact
AIMD GPDS Courses
  • Home
  • Courses
  • Contact
  • More
    • Home
    • Courses
    • Contact

日本語  ❯

Lesson 1    ❮    Lesson List    ❮    Top Page

1.1 Variables

1.2 Strings

1.3 Numbers

❯  1.4  Lists

1.5 List Methods

1.6 Slice Operator   

⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺
EXPECTED COMPLETION TIME
❲▹❳  Video   7m 41s
☷  Interactive readings   5m

Making a List

A list is a collection of items with its own order. The list can contains alphabet, 0-9, strings, etc. 

In Python, square brackets ([]) indicate a list, and each element in the list are separated by commas.

Accessing Elements in a List

To get an element in a list, we need the index of the item we want. For the 1st element of the list, write [0] at the end of the list name.

1st element  = index 0,
2nd element = index 1,
3rd element = index 2 , and so on.

Just like variables, methods can also be used here.

Using Negative Index on List

To get the last element in the list, we can use the index -1.

Last element = index -1,
2nd-to-last element = index -2,
3rd-to-last element = index -3, and so on

Changing Elements in a List

The method for changing an element in a list is the same as the method for getting an element in a list. 

We can simply use = and the desired index as the following example.

WRITE BETTER CODE
Writing Long List Neatly

It is recommended to split the long list into few lines for readability. One line can have 3-5 items. 

Don't forget to add 1 space after each comma as well. 

LEARN FROM ERRORS
IndexError in List

Since Python counts the element from index 0, it can be confusing at first to get the element that we want.

One common error is when we give index that is larger than the size of the list.

One way to resolve this error is to change list_length into list_length - 1.

©2023. All rights reserved.  Samy Baladram,
Graduate Program in Data Science - GSIS - Tohoku University
Google Sites
Report abuse
Page details
Page updated
Google Sites
Report abuse