» Quick Introduction to Python » 2. Collections » 2.1 Lists

Lists

Construct a List

a = [1, 2, 3]
b = list("lite") # ['l', 'i', 't', 'e']

Access Item

a = ["Lite", 1, 3.14, False]
print(a[2]) # 3.14

Update Item

a = ["Lite", 1, 3.14]
a[1] = "Rank"
print(a) # ['Lite', 'Rank', 3.14]

List's Common Methods

append

a = [1, 2]
a.append(3)
print(a) # [1, 2, 3]

clear

a = [1, 2]
a.clear()
print(a) # []

copy

a = [1, 2]
b = a.copy()
print(b) # [1, 2]

extend

a = [1, 2]
b = [3, 4]
a.extend(b)
print(a) # [1, 2, 3, 4]

insert

a = ["apple", "banana", "cherry"]
a.insert(1, "grape")
print(a) # ['apple', 'grape', 'banana', 'cherry']

reverse

a = [3, 9, 27, 78]
a.reverse()
print(a) # [78, 27, 9, 3]

sort

a = ["banana", "grape", "cherry", "apple"]
a.sort()
print(a) # ['apple', 'banana', 'cherry', 'grape']

Code Challenge

Try to modify the code provided in the editor to sort the list by the length of each item. If two items share the same length, sort them alphabetically.

Loading...
> code result goes here
Prev
Next