Python Language List: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 61: Line 61:


=List Processing=
=List Processing=
==<tt>split()</tt>/<tt>join()</tt>==
==<tt>split()</tt>, <tt>join()</tt>==
 
==Join the List Elements in a String==
==Join the List Elements in a String==
Join the elements of the given list in a string, using '-' as separator:
Join the elements of the given list in a string, using '-' as separator:

Revision as of 23:23, 6 March 2022

Internal

Overview

A list is a mutable sequence type that contains zero or more elements and whose elements can be of different types.

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

Access a List

Test for Empty List

Test for Existence of an Element in List

Size 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

Assign the sublist to l:

l = l[:-1]

Modify a List

Modify Individual Elements

Append an Element

l.append(e)

Delete the Last Element

del l[-1]

Delete All Elements

List Processing

split(), join()

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