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   10m 21s
☷  Interactive readings   5m

Adding Elements to a List

There are two ways to add a new element to a list. 

append(item)
adds item to the end of list.

insert(pos, item)
adds item to the index pos in the list.

Deleting Elements of a List

You can use the following method to delete element of a list.

pop(pos)
deletes the element with index pos (default is -1). It is also possible to save the popped item into a variable.

remove(itemname)
deletes the element with the name itemname. 

Sorting Elements of a List

Sorting elements in a list can be done easily using the following:

sort()
sorts the list.

reverse()
reverses the order of a list.

Combining List

You can combine two lists by the following:

list1.extend(list2)
combines list1 with list2.

To make a separate list, use + instead.

Getting Index & Count of the Elements

You can get the index and the count number of an item name in a list using the following:

index(itemname)
returns the index of the first element with the name itemname.

count(itemname)
returns the number of elements with the name itemname. 

WRITE BETTER CODE
Applying List Method to a String

The list methods in this lesson can be applied as well to a string. Each character in a string can be treated like a single item in a list.

LEARN FROM ERRORS
Assigning Variable to a Non-return Method 

Some methods can be used with or without assigning it to a variable, like pop(). However, assigning other methods to a variable will return a NoneType object. This will give an AttributeError.

To fix this error, remove names =  from Line 3 and 4.

©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