Skip to content

Instantly share code, notes, and snippets.

@pknowledge
Created September 2, 2018 16:25
Show Gist options
  • Save pknowledge/fd3cf256b75a030ac47a5a2c276a58bf to your computer and use it in GitHub Desktop.
Save pknowledge/fd3cf256b75a030ac47a5a2c276a58bf to your computer and use it in GitHub Desktop.
Python Lists
>>> x = [3, 5, 4, 9, 7, 10]
>>> x
[3, 5, 4, 9, 7, 10]
>>> x[0]
3
>>> x[4]
7
>>> y = ['max', 1, 15.5, [3, 2]]
>>> y[0]
'max'
>>> y[3]
[3, 2]
>>> y[100]
Traceback (most recent call last):
File "<input>", line 1, in <module>
IndexError: list index out of range
>>> len(x)
6
>>> len(y)
4
>>> x.insert(2, 'tom')
>>> x
[3, 5, 'tom', 4, 9, 7, 10]
>>> x.remove('tom')
>>> x
[3, 5, 4, 9, 7, 10]
>>> x.insert(1, 3)
>>> x
[3, 3, 5, 4, 9, 7, 10]
>>> x.remove(3)
>>> x
[3, 5, 4, 9, 7, 10]
>>> x.remove(100)
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> x.pop()
10
>>> x
[3, 5, 4, 9, 7]
>>> x.pop()
7
>>> x
[3, 5, 4, 9]
>>> z = [1,2,5,4]
>>> z
[1, 2, 5, 4]
>>> del z
>>> z
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'z' is not defined
>>> z = [1,2,5,4]
>>> z.clear()
>>> z
[]
>>> x
[3, 5, 4, 9]
>>> x.sort()
>>> x
[3, 4, 5, 9]
>>> x.reverse()
>>> x
[9, 5, 4, 3]
>>> x.append(10)
>>> x
[9, 5, 4, 3, 10]
>>> s = x.copy()
>>> s
[9, 5, 4, 3, 10]
>>> x.append(10)
>>> x
[9, 5, 4, 3, 10, 10]
>>> x.count(10)
2
>>> x.count(3)
1
>>> x.count(100)
0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment