My Coding > Programming language > Python > Python LIST HowTo

Python LIST HowTo (Page: 2)

Go to Page:

  1. List in Python;
  2. Python List Cheat Sheet;
  3. How To copy List in Python;

Python List Cheat Sheet

A container data type that stores a sequence of elements. Unlike strings, lists are mutable: modification possible.


L = [1, 3, 3]
print(len(L)) # 3

You can add element to list with append, insert or concatenate. Append is very fast

Please note, append and insert returns None!


[1, 3, 3].append(4)        # [1, 3, 3, 4]
print([1, 3, 3].append(4)) # None
[1, 3, 3].insert(1, 2)     # [1, 2, 3, 3]
[1, 3, 3] + [4]            # [1, 3, 3, 4]

Remove first occurence of element - a bit slow. Remove returns None


[1, 2, 1, 2].remove(2) # [1, 1, 2]

Reverse list of elements can be done with reverse() of slices

Reverse return None!


[1, 2, 3].reverse()    # [3, 2, 1]
print([1, 2, 3][::-1]) # [3, 2, 1]

Sorting of list (complexity is proportional to N)


[2, 5, 3].sort() # [2, 3, 5]

Find first occurence of element with index()


[2, 4, 2].index(2)   # 0
[2, 4, 2].index(2,1) # 2 - index of element 2 after position 1

Use combination of append() and pop() to emulate stack behavious

pop() returns popped element


stack = [10]    # [10]
stack.append(4) # [10, 4]
stack.pop()     # 4 [10]
stack.pop()     # 10 []

List comprehension

List comprehension is the concise Python way to create lists.


l1 = [('This is ' + x) for x in ['apple', 'pear', 'cherry']]
print(l1) # ['This is apple', 'This is pear', 'This is cherry']

l2 = [x * y for x in range(3) for y in range(3) if x>y]
print(l2) # [0, 0, 2]

Python list at glance

Python list at glance


list.append(x)                 # Add element to the end of list
list.extend(L)                 # Add eleemnts frim list L
list.insert(i, x)              # Insert x into position i
list.remove(x)                 # remove first element with value x or raise error
list.pop([i])                  # remove element number i
list.index(x, [start [, end]]) # posision of element x. Search from start to end
list.count(x)                  # count all elements x
list.sort([key=function])      # List sorting on the basis of given function
list.reverse()                 # reverse order of the list
list.copy()                    # shallow copy of the list
list.clear()                   # clearing the list

Go to Page: 1; 2; 3;


Published: 2021-09-13 08:23:41
Updated: 2021-10-24 11:58:41

Last 10 artitles


9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.