DEV Community

Super Kai (Kazuya Ito)
Super Kai (Kazuya Ito)

Posted on • Edited on

List in Python (1)

Buy Me a Coffee

*Memo:

  • My post explains the list with slicing and copy.
  • My post explains list functions (1).
  • My post explains list functions (2).
  • My post explains the shallow copy and deep copy of a list.
  • My post explains a tuple.
  • My post explains a set and the set with copy.
  • My post explains a dictionary (1).
  • My post explains an iterator (1).
  • My post explains a string.
  • My post explains a bytes.
  • My post explains a bytearray.

A list:

  • is the ordered collection of zero or more elements whose type is list:
    • Ordered means that the order of the elements in a list is kept so it guarantees that the order is always the same unless someone or something changes it.
  • should use non-huge data not to get MemoryError.
  • allows duplicated elements (even with different types).
  • is mutable so it can be changed.
  • can have any types of elements.
  • can be iterated with a for statement.
  • can be unpacked with an assignment and for statement, function and * but not with **.
  • is False if it's empty.
  • can be checked if a specific element is or isn't in it with in keyword or not and in keyword respectively.
  • can be checked if it is or isn't referred to by two variables with is keyword or not and is keyword respectively.
  • can be enlarged with * and a number.
  • can be created by [], list() with or without an iterable or a list comprehension:
    • For list(), the words type conversion are also suitable in addition to the word creation.
  • can be used with len() to get the length.
  • can be read or changed by indexing or slicing.
  • can be continuously used through multiple variables.
  • can be copied to refer to a different list.

A list is for non-huge data otherwise it gets MemoryError.


[] can create a list as shown below:

v = []                     # Empty 1D list
v = [0, 1, 2, 3, 4, 5]     # 1D list
v = [0, 1, 2, 0, 1, 2]     # 1D list
v = [0, 1, [2, 3, 4, 5]]   # 2D list
v = [0, 1, [2, 3, [4, 5]]] # 3D list
# No error

v = [0, 0.0, 0.0+0.0j, False]
v = ['A', b'A', bytearray(b'A'), 2, 2.3, 2.3+4.5j, True,
     [2, 3], (2, 3), {2, 3}, frozenset({2, 3}),
     {'A':'a'}, range(2, 3), iter([2, 3])]
for v in [0, 1, 2]: pass
v1, v2, v3 = [0, 1, 2]
v1, *v2, v3 = [0, 1, 2, 3, 4, 5]
for v1, v2, v3 in [[0, 1, 2], [3, 4, 5]]: pass
for v1, *v2, v3 in [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]]: pass
print([*[0, 1, *[2]], *[3, 4]])
print(*[0, 1, *[2]], *[3, 4])
v = [0, 1, 2] * 3
v = [[0, 1, 2]] * 3
v = [[[0, 1, 2]]] * 3
v = [x**2 for x in range(6)]
# No error

print(**[0, 1, 2, 3, 4])
v = ['A', 'B', 'C'] * 1000000000
# Error
Enter fullscreen mode Exit fullscreen mode

A list is the ordered collection of zero or more elements whose type is list as shown below:

v = [0, 1, 2, 3, 4, 5]

print(v)
# [0, 1, 2, 3, 4, 5]

print(type(v))
# <class 'list'>
Enter fullscreen mode Exit fullscreen mode
v = [] # Empty list

print(v)
# []
Enter fullscreen mode Exit fullscreen mode

A list allows duplicated elements (even with different types) as shown below:

v = [0, 1, 2, 0, 1, 2]

print(v)
# [0, 1, 2, 0, 1, 2]
Enter fullscreen mode Exit fullscreen mode
v = [0, 0.0, 0.0+0.0j, False]

print(v)
# [0, 0.0, 0j, False]
Enter fullscreen mode Exit fullscreen mode
v = [1, 1.0, 1.0+0.0j, True]

print(v)
# [1, 1.0, (1+0j), True]
Enter fullscreen mode Exit fullscreen mode

A list can have any types of elements as shown below:

v = ['A', b'A', bytearray(b'A'), 2, 2.3, 2.3+4.5j, True,
     [2, 3], (2, 3), {2, 3}, frozenset({2, 3}),
     {'A':'a'}, range(2, 3), iter([2, 3])]
print(v)
# ['A', b'A', bytearray(b'A'), 2, 2.3, (2.3+4.5j), True,
#  [2, 3], (2, 3), {2, 3}, frozenset({2, 3}), {'A': 'a'},
#  range(2, 3), <list_iterator object at 0x000001F3BA8A6560>]
Enter fullscreen mode Exit fullscreen mode

A list can be iterated with a for statement as shown below:

for v in [0, 1, 2]:
    print(v)
# 0
# 1
# 2
Enter fullscreen mode Exit fullscreen mode

A list can be unpacked with an assignment and for statement, function and * but not with ** as shown below:

v1, v2, v3 = [0, 1, 2]

print(v1, v2, v3)
# 0 1 2
Enter fullscreen mode Exit fullscreen mode
v1, *v2, v3 = [0, 1, 2, 3, 4, 5]

print(v1, v2, v3)  # 0 [1, 2, 3, 4] 5
print(v1, *v2, v3) # 0 1 2 3 4 5
Enter fullscreen mode Exit fullscreen mode
for v1, v2, v3 in [[0, 1, 2], [3, 4, 5]]:
    print(v1, v2, v3)
# 0 1 2
# 3 4 5
Enter fullscreen mode Exit fullscreen mode
for v1, *v2, v3 in [[0, 1, 2, 3, 4, 5],
                    [6, 7, 8, 9, 10, 11]]:
    print(v1, v2, v3)
    print(v1, *v2, v3)
# 0 [1, 2, 3, 4] 5
# 0 1 2 3 4 5
# 6 [7, 8, 9, 10] 11
# 6 7 8 9 10 11
Enter fullscreen mode Exit fullscreen mode
def func(p1='a', p2='b', p3='c', p4='d', p5='e', p6='f'):
    print(p1, p2, p3, p4, p5, p6)

func()
# a b c d e f

func(*[0, 1, 2, 3], *[4, 5])
# 0 1 2 3 4 5
Enter fullscreen mode Exit fullscreen mode
def func(p1='a', p2='b', *args):
    print(p1, p2, args)
    print(p1, p2, *args)
    print(p1, p2, ['A', 'B', *args, 'C', 'D'])

func()
# a b ()
# a b Nothing
# a b ['A', 'B', 'C', 'D']

func(*[0, 1, 2, 3], *[4, 5])
# 0 1 (2, 3, 4, 5)
# 0 1 2 3 4 5
# 0 1 ['A', 'B', 2, 3, 4, 5, 'C', 'D']
Enter fullscreen mode Exit fullscreen mode
print([*[0, 1, *[2]], *[3, 4]])
# [0, 1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode
print(*[0, 1, *[2]], *[3, 4])
# 0 1 2 3 4
Enter fullscreen mode Exit fullscreen mode
print(**[0, 1, 2, 3, 4])
# TypeError: print() argument after ** must be a mapping, not list
Enter fullscreen mode Exit fullscreen mode

An empty list is False as shown below:

print(bool([]))   # Empty list
# False

print(bool([0]))  # list
print(bool([[]])) # list(Empty list)
# True
Enter fullscreen mode Exit fullscreen mode

A list can be checked if a specific element is or isn't in it with in keyword or not and in keyword respectively as shown below:

v = ['A', 'B', ['C', 'D']]

print('B' in v)
# True

print(['C', 'D'] in v)
# True

print('b' in v)
# False
Enter fullscreen mode Exit fullscreen mode
v = ['A', 'B', ['C', 'D']]

print('B' not in v)
# False

print(['C', 'D'] not in v)
# False

print('b' not in v)
# True
Enter fullscreen mode Exit fullscreen mode

A list can be enlarged with * and a number as shown below:

1D list:

v = [0, 1, 2] * 3

print(v)
# [0, 1, 2, 0, 1, 2, 0, 1, 2]
Enter fullscreen mode Exit fullscreen mode
v = ['A', 'B', 'C'] * 3

print(v)
# ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C']
Enter fullscreen mode Exit fullscreen mode
v = [] * 3

print(v)
# []
Enter fullscreen mode Exit fullscreen mode

2D list:

v = [[0, 1, 2]] * 3

print(v)
# [[0, 1, 2], [0, 1, 2], [0, 1, 2]]
Enter fullscreen mode Exit fullscreen mode
v = [['A', 'B', 'C']] * 3

print(v)
# [['A', 'B', 'C'], ['A', 'B', 'C'], ['A', 'B', 'C']]
Enter fullscreen mode Exit fullscreen mode
v = [[]] * 3

print(v)
# [[], [], []]
Enter fullscreen mode Exit fullscreen mode

3D list:

v = [[[0, 1, 2]]] * 3

print(v)
# [[[0, 1, 2]], [[0, 1, 2]], [[0, 1, 2]]]
Enter fullscreen mode Exit fullscreen mode
v = [[['A', 'B', 'C']]] * 3

print(v) 
# [[['A', 'B', 'C']], [['A', 'B', 'C']], [['A', 'B', 'C']]]
Enter fullscreen mode Exit fullscreen mode
v = [[[]]] * 3

print(v)
# [[[]], [[]], [[]]]
Enter fullscreen mode Exit fullscreen mode

list() can create a list with or without an iterable as shown below:

*Memo:

  • The 1st argument is iterable(Optional-Default:()-Type:Iterable):
    • Don't use iterable=.
# Empty list
print(list())
print(list(()))
# []

print(list([0, 1, 2, 3, 4]))                      # list
print(list((0, 1, 2, 3, 4)))                      # tuple
print(list({0, 1, 2, 3, 4}))                      # set
print(list(frozenset({0, 1, 2, 3, 4})))           # frozenset
print(list(iter([0, 1, 2, 3, 4])))                # iterator
print(list(range(5)))                             # range
# [0, 1, 2, 3, 4]

print(list({'name': 'John', 'age': 36}))          # dict
print(list({'name': 'John', 'age': 36}.keys()))   # dict.keys()
# ['name', 'age']

print(list({'name': 'John', 'age': 36}.values())) # dict.values()
# ['John', 36]

print(list({'name': 'John', 'age': 36}.items()))  # dict.items()
# [('name', 'John'), ('age', 36)]

print(list('Hello'))                              # str
# ['H', 'e', 'l', 'l', 'o']

print(list(b'Hello'))                             # bytes
print(list(bytearray(b'Hello')))                  # bytearray
# [72, 101, 108, 108, 111]
Enter fullscreen mode Exit fullscreen mode

A list comprehension can create a list as shown below:

v = [x**2 for x in range(6)]

print(v)
# [0, 1, 4, 9, 16, 25]
Enter fullscreen mode Exit fullscreen mode

Be careful, a huge list gets MemoryError as shown below:

v = [0, 1, 2] * 1000000000
# MemoryError
Enter fullscreen mode Exit fullscreen mode
v = range(100000000)

print(list(v))
# MemoryError
Enter fullscreen mode Exit fullscreen mode

A list can be used with len() to get the length as shown below:

v = [0, 1, 2, 3, 4]

print(len(v))
# 5
Enter fullscreen mode Exit fullscreen mode

A list can be read or changed by indexing as shown below:

*Memo:

  • Indexing can be done with one or more [index].
  • A del statement can remove one or more elements from a list by indexing and can remove one or more variables themselves.

1D list:

v = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

print(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7])
print(v[-8], v[-7], v[-6], v[-5], v[-4], v[-3], v[-2], v[-1])
# a b c d e f g h

v[1] = 'B'
v[-7] = 'B'

v[3] = 'D'
v[-5] = 'D'

v[6] = 'G'
v[-2] = 'G'

print(v)
# ['a', 'B', 'c', 'D', 'e', 'f', 'G', 'h']

del v[1], v[2], v[4]
# del v[-7], v[-5], v[-2]

print(v)
# ['a', 'c', 'e', 'f', 'h']

del v

print(v)
# NameError: name 'v' is not defined
Enter fullscreen mode Exit fullscreen mode

2D list:

v = [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h']]

print(v[0], v[1])
print(v[-2], v[-1])
# ['a', 'b', 'c', 'd'] ['e', 'f', 'g', 'h']

print(v[0][0], v[0][1], v[0][2], v[0][3], v[1][0], v[1][1], v[1][2], v[1][3])
print(v[-2][-4], v[-2][-3], v[-2][-2], v[-2][-1],
      v[-1][-4], v[-1][-3], v[-1][-2], v[-1][-1])
# a b c d e f g h

v[0][1] = 'B'
v[-2][-3] = 'B'

v[1] = ['E', 'F', 'G', 'H']
v[-1] = ['E', 'F', 'G', 'H']

print(v)
# [['a', 'B', 'c', 'd'], ['E', 'F', 'G', 'H']]

del v[0][1], v[1]
# del v[-2][-3], v[-1]

print(v)
# [['a', 'c', 'd']]
Enter fullscreen mode Exit fullscreen mode

3D list:

v = [[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]

print(v[0], v[1])
print(v[-2], v[-1])
# [['a', 'b'], ['c', 'd']] [['e', 'f'], ['g', 'h']]

print(v[0][0], v[0][1], v[1][0], v[1][1])
print(v[-2][-2], v[-2][-1], v[-1][-2], v[-1][-1])
# ['a', 'b'] ['c', 'd'] ['e', 'f'] ['g', 'h']

print(v[0][0][0], v[0][0][1], v[0][1][0], v[0][1][1], v[1][0][0],
      v[1][0][1], v[1][1][0], v[1][1][1])
print(v[-2][-2][-2], v[-2][-2][-1], v[-2][-1][-2], v[-2][-1][-1],
      v[-1][-2][-2], v[-1][-2][-1], v[-1][-1][-2], v[-1][-1][-1])
# a b c d e f g h

v[0][0][1] = 'B'
v[-2][-2][-1] = 'B'

v[0][1] = 'C'
v[-2][-1] = 'C'

v[1] = ['D', ['E', 'F']]
v[-1] = ['D', ['E', 'F']]

print(v)
# [[['a', 'B'], 'C'], ['D', ['E', 'F']]]

del v[0][0][1], v[0][1], v[1]
# del v[-2][-2][-1], v[-2][-1], v[-1]

print(v)
# [[['a']]]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)