0
.x[1:4]
gives elements from x[1]
to x[3]
inclusive (takes 1
, not 4
).x[:3] + x[3:]
gives exactly x
.Ordered (different order, different list):
x = [1, 2]
y = [1, 2]
z = [2, 1]
x == y
x == z
True
False
Mutable (we can change elements in list),
x = [1, 2, 3]
x[1] = 5
print(x)
# change mutiple elements
y = [1, 2, 3, 4, 5]
y[1:3] = [20, 30]
print(y)
[1, 5, 3]
[1, 20, 30, 4, 5]
Directly,
x = [1, "Thi", 3] # mixed datatypes
y = [[1, 2, 3],
[4, 5, 6]] # nested list
z = [] # empty list
print(x)
print(y)
print(z)
[1, 'Thi', 3]
[[1, 2, 3], [4, 5, 6]]
[]
From other types,
a = (1, 2, 3) # tuple
x = list(a)
print(a)
print(x)
(1, 2, 3)
[1, 2, 3]
With for
(List comprehensions),
x = [i for i in range(4)]
print(x)
[0, 1, 2, 3]
# list comprehension with if
[e for e in lst if e>0]
# list comprehension with if else
[x+1 if x >= 45 else x+5 for x in l]
# 2 fors in list comprehension
[(x,y) for x in seq_x for y in seq_y]
[entry for tag in tags for entry in entries if tag in entry]
a = [[1,2], [3,4]]
{i for e in a for i in e}
# {1, 2, 3, 4}
Create a list from range,
[*range(10, 21, 1)]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]