Python lists

Introduction

To create a list you need to use square brackets []

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

['a','b','c']

The result is a list of three elements. Each one has a unique index.

The index of 'a' = 0, the index of 'b' = 1, the index of 'c' = 2.

You can also use the index in the opposite direction. Then the index of c = -1, the index of b = -2, the index of a = -3

Elementabc
Index012
Index --3-2-1

Slicing a list

l = [100, 200, 300, 400, 500] print("l: ", l) print("l[0]:\n", l[0]) print("l[-0]:\n", l[-0]) print("l[1]:\n", l[1]) print("l[-1]:\n", l[-1]) print("l[1:3]:\n", l[1:3]) print("l[1:-1]:\n", l[1:-1]) print("l[2:]:\n", l[2:]) print("l[:2]:\n", l[:2]) # All list elements print("l[:]:\n", l[:])

l[0]: 100 l[-0]: 100 l[1]: 200 l[-1]: 500 l[1:3]: [200, 300] l[1:-1]: [200, 300, 400] l[2:]: [300, 400, 500] l[:2]: [100, 200] l[:]: [100, 200, 300, 400, 500]

Copying a list

# Copy l = [100, 200, 300, 400, 500] t = l print("\n# t = l") print("t is l =", t is l) # True r = l[:] print("\n# r = l[:]") print("r is l = ", r is l) # False print("r == l = ", r == l) # True u = l.copy() print("\n# u = l.copy()") print("u is l = ", u is l) # False v = list(l) print("\n# v = list(l)") print("v is l = ", v is l) # False

# t = l t is l = True # r = l[:] r is l = False r == l = True # u = l.copy() u is l = False # v = list(l) v is l = False

a = [ [1, 2], [3, 4] ] b = a[:] print(a is b) # False print(a == b) # True print(a[0]) # [1, 2] print(b[0]) # [1, 2] print(a[0] is b[0]) # True a[0] = [8, 9] print(a[0]) # [8, 9] print(b[0]) # [1, 2] a[1].append(5) print(a[1]) # [3, 4, 5] print(b[1]) # [3, 4, 5] print(a) # [[8, 9], [3, 4, 5]] print(b) # [[1, 2], [3, 4, 5]]

False True [1, 2] [1, 2] True [8, 9] [1, 2] [3, 4, 5] [3, 4, 5] [[8, 9], [3, 4, 5]] [[1, 2], [3, 4, 5]]

Multiplication can be applied to lists

s = [ [-1, +1] ] * 5 print(s) s[2].append(7) print(s)

[21, 37, 21, 37, 21, 37, 21, 37] [0, 0, 0, 0, 0, 0, 0, 0, 0]

The most surprising manifestation of the fact that Python uses merely references to objects can be observed precisely when creating lists by multiplication

s = [ [-1, +1] ] * 5 print(s) s[2].append(7) print(s)

[[-1, 1], [-1, 1], [-1, 1], [-1, 1], [-1, 1]] [[-1, 1, 7], [-1, 1, 7], [-1, 1, 7], [-1, 1, 7], [-1, 1, 7]]

As you can see, the seven was added everywhere because the original object from which the list was created by multiplication was changed

w = "the heihei.ru website was forked from aredel.com in 2018 simultaneously with the topbicyle.ru website".split() print(w) i = w.index('was') print(i) # 3 print(w[i]) # was print(w.count("the")) # 2 print("heihei.ru" in w) # True print("urn.su" not in w) # True

['the', 'heihei.ru', 'website', 'was', 'forked', 'from', 'aredel.com', 'in', '2018', 'simultaneously', 'with', 'the', 'topbicyle.ru', 'website'] 3 was 2 True True

len()

You can find the length of a list with the function len()

>>> l = ["Pluralsight", "OTUS", "GeekBrains"]
>>> print(len(l))

3

append()

To add a new element to the end of a list, the method is used append()

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

['a','b','c','d']

print(len(l))

4

Other ways to add to a list

>>> a = [0, 1, 2] >>> b = [3, 4, 5] >>> c = a + b >>> c [0, 1, 2, 3, 4, 5] >>> c += [6, 7, 8] >>> c [0, 1, 2, 3, 4, 5, 6, 7, 8] >>> c.extend([9, 10, 11]) >>> c [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

insert()

To add a new element to the beginning of a list, the method is used insert()

l.insert(0, 'z')
print(l)

['z','a','b','c','d']

print(len(l))

5

With insert() you can insert an element anywhere in the list

You need to pass to insert() the index of the place where you want to put the element

l.insert(3, 'j')
print(l)

['z','a','b','j','c','d']

print(len(l))

6

split() and join()

You can turn a string into a list with split()

Assemble a list into a string - with join()

>>> s = 'Please visit website' >>> s 'Please visit website' >>> a = s.split() >>> a ['Please', 'visit', 'website'] >>> a.insert(2, "topbicycle.ru") >>> a ['Please', 'visit', 'topbicycle.ru', 'website'] >>> s = ' '.join(a) >>> s 'Please visit topbicycle.ru website'

To remove the last element of a list, the method is used pop()

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

['a', 'b']

print(len(l))

2

pop(0)

To remove the first element of a list

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

['b', 'c']

print(len(l))

2

To remove an arbitrary element of a list, pass to pop() its index

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

['a', 'c']

print(len(l))

2

del

You can remove elements from a list with del

>>> c = "Armenia Finland Georgia Germany Italy Norway Russia Spain Sweden".split() >>> c ['Armenia', 'Finland', 'Georgia', 'Germany', 'Italy', 'Norway', 'Russia', 'Spain', 'Sweden'] >>> del c[3] >>> c ['Armenia', 'Finland', 'Georgia', 'Italy', 'Norway', 'Russia', 'Spain', 'Sweden'] >>> c.remove('Norway') >>> c ['Armenia', 'Finland', 'Georgia', 'Italy', 'Russia', 'Spain', 'Sweden'] >>> del c[c.index('Sweden')] >>> c ['Armenia', 'Finland', 'Georgia', 'Italy', 'Russia', 'Spain']

reverse() and sort()

>>> d = [1, 5, 70] >>> d.reverse() >>> d [70, 5, 1] >>> e = [8, 3, 14] >>> e.sort() >>> e [3, 8, 14] >>> e.sort(reverse=True) >>> e [14, 8, 3]

>>> w = 'Please visit topbicycle.ru website'.split() >>> w ['Please', 'visit', 'topbicycle.ru', 'website'] >>> w.sort(key=len) >>> w ['visit', 'Please', 'website', 'topbicycle.ru']

>>> x = [4, 9, 2, 1] >>> y = sorted(x) >>> y [1, 2, 4, 9] >>> x [4, 9, 2, 1] >>> p = [9, 3, 1, 0] >>> q = reversed(p) >>> q <list_reverseiterator object at 0x7f93ddd42280> >>> list(q) [0, 1, 3, 9]

zip

With the function zip() you can create a list of tuples from two lists.

>>> languages = ['Java', 'Python', 'JavaScript'] >>> versions = [18, 3, 2015] >>> result = zip(languages, versions) >>> print(list(result))

[('Java', 18), ('Python', 3), ('JavaScript', 2015)]

How to create lists

Using a for loop

You can use a for loop to create a list.

This is done in three steps

  1. Create an empty list
  2. Iterate over an iterable object or several objects.
  3. Append each element to the end of the list

If you want to create a list containing the first ten perfect squares, you can perform these steps in three lines of code:

>>> squares = [] >>> for i in range(10): ... squares.append(i * i) >>> squares

Or even in two

>>> squares = [] >>> for i in range(10): squares.append(i * i) >>> squares

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

First an empty list, squares, is created.

Then, using a for loop, iteration over range(10) takes place.

Finally, each number is multiplied by itself and the result is appended to the end of the list.

Using map()

map() provides an alternative approach based on functional programming.

map() is passed a function and an iterable object and map() creates a new iterable object.

o = map(function, iterable)

This object contains the output that would have resulted if, to each element of the original iterable object — one had applied the given function

As an example, consider a situation in which you need to calculate the price after tax for a list of transactions:

txns = [1.11, 23.45, 45.5, 61.4] TAX_RATE = .08 def get_price_with_tax(txn): return txn * (1 + TAX_RATE) final_prices = map(get_price_with_tax, txns) print(list(final_prices))

[1.1988, 25.326, 49.14, 66.312]

Here you have an iterable txns and the function get_price_with_tax(). You pass both of these arguments to map() and store the resulting object in final_prices.

You can easily convert this map object into a list with the list() function.

Banner image

List abstraction

List Comprehension - list abstraction, or list inclusion, or a list generator.

The third way to create lists is list comprehension.

With this elegant approach you can rewrite the for loop from the first example in just one line:

>>> squares = [i * i for i in range(10)] >>> squares

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

You can read more about this method in the article «List Comprehension in Python»

Article author: Andrei Olegovich