Python Language List: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 122: Line 122:
</syntaxhighlight>
</syntaxhighlight>


===Append a List===
===<span id='extend'></span>Append a List===
A list can be extended with another list with the <code>extend()</code> function:
A list can be extended with another list with the <code>extend()</code> function:
<syntaxhighlight lang='py'>
<syntaxhighlight lang='py'>

Revision as of 02:35, 7 March 2022

Internal

Overview

A list is a mutable sequence type that contains zero or more elements and whose elements can be of the same type or different types. The elements of a list are ordered. As mentioned, the list is mutable, in that a list can be changed in-place, new elements can be added to it, and existing elements can be overwritten. Unlike a set, a list can contain the same element multiple times, a list element does not need to be unique in the list.

List type()

The function type() applied to a list returns: <class 'list'>

To check whether an instance is a list:

i = ...
if type(i) is list:
  ...

For list subclasses:

i = ...
if isinstance(i, list):
  ...

Create a List

A list can be created with the [] syntax, with the list() functions and with list comprehensions.

Create a List with []

A list can be created specifying the list elements, separate them by comma and enclose them in square brackets.

empty_list = []
some_list = ['A', 'B', 'C']
some_other_list = ['A', 2, 3.0, ['B', 4]]

Create a List or Convert other Data Type to a List with list()

An empty list can be created with the list() function:

empty_list = list()

The list() function converts the data types to lists. The data types that can be converted are:

String to List

s = 'abc'
l = list(s) # l is ['a', 'b', 'c']

Tuple to List

t = ('a', 'b', 'c')
l = list(t) # l is ['a' ,'b', 'c']

Access a List

Test for Empty List

Test for Existence of an Element in List

Access an Element in List

The element of a list can be accessed using the [<offset>] syntax. The offset is zero-based, and it can be positive or negative.

l = ['a', 'b', 'c']
print(l[0])

Negative indices count backward from the end, the last element is identified with a -1 index. Think about it as index = len(list) - negative-index.

l = ['a', 'b', 'c']
print(l[-1]) # displays "c"
print(l[-2]) # displays "b"

⚠️ In case of both positive and negative indices, the offset should be valid. If the indices fall outside of the list's bounds, IndexError: list index out of range exception is thrown.

Length of a List

The number of elements is given by the len() function:

l = [...]
print(len(l))

Iterate over a List

l = ['A', 'B', 'C']
for i, e in enumerate(l):
    print(f'index: {i}, element: {e}')

Slices

A sub-sequence of a list can be extracted with a slice. The slice [<start-index>:<end-index>:<step>] specified the index of the last element, and the index of the first element not included in slice, and the step. The step is optional, the default value is 1.

l = ['a', 'b', 'c', 'd', 'e', 'f']
print(l[:]) # starts from the beginning and ends after the end of the list, prints ['a', 'b', 'c', 'd', 'e', 'f']
print(l[2:4]) # prints ['c', 'd']
print(l[2:4:2]) # prints ['c']

The step can be negative, which means the slice starts at the end and goes from right to left.

l = ['a', 'b', 'c', 'd', 'e', 'f']
print(l[::-1]) # prints ['f', 'e', 'd', 'c', 'b', 'a']

Assign the sublist to l:

l = l[:-1]

Modify a List

Modify Individual Elements

Modify an Element Identified by []

An element of a list can be modified using the [<offset>] syntax. The offset is zero-based, and it can be positive or negative, as described in Access an Element in List.

l = ['a', 'b', 'c']
l[1] = 'd'
print(l[1])

Append an Element

The traditional way of adding items to a list is to append() them one by one to the end of the list. The invocation increases the length of the list.

l = [1, 2, 3]
l.append(10)
print(l) # will display [1, 2, 3, 10]

Append a List

A list can be extended with another list with the extend() function:

l1 = [1, 2, 3]
l2 = [10, 20]
l1.extend(l2)
print(l1) # will display [1, 2, 3, 10, 20]

The extend() function is equivalent with the += operator:

l1 = [1, 2, 3]
l2 = [10, 20]
l1 += l2
print(l1) # will display [1, 2, 3, 10, 20]

Delete the Last Element

del l[-1]

Delete All Elements

List Processing

split(), join()

A string can be converted into a list containing tokens delimited by separators in the string using the split() function. split() is a string function. The elements of the newly created list are strings.

s='a b c'
l = s.split(' ') # l is ['a', 'b', 'c']

If two separators occur in succession in the string, the list contains an empty string:

s='a,,b,c'
l = s.split(',') # l is ['a', '', 'b', 'c']

Sorting

TO DEPLETE

Join the List Elements in a String

Join the elements of the given list in a string, using '-' as separator:

li = ['a', 'b']
s = '-'.join(li)

Only works if the list elements are strings.

Extract Elements from the Tail of the List Starting with a Certain Index

l = [1, 2, 3]
print(l[0:]) # prints [1, 2, 3]
print(l[1:]) # prints [2, 3]
print(l[2:]) # prints [3]
print(l[3:]) # prints [] (empty list)
print(l[4:]) # prints [] (empty list)

Extract Elements from the Head of the List Counting from the Tail

TODO

Copy a List

Multi-Dimensional Lists

m = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
print(m[2][1]) # prints 8