Lists

Lists are constructed with square brackets with elements separated by a comma.

Lists are mutable, meaning the individual items in the list can be changed.

Example 1


In [1]:
vowels = ['a','e','i','o','u']
print(vowels)


['a', 'e', 'i', 'o', 'u']

Example 2

Lists can also hold multiple object types


In [2]:
list1 = [1,'a',"This is a list",5.25]
print(list1)


[1, 'a', 'This is a list', 5.25]

Example 3


In [3]:
# Find the length of the list
len(list1)


Out[3]:
4

Example 4 - Slicing & Indexing


In [4]:
# Get the element using the index
print(list1[0])
print(list1[2])


1
This is a list

In [17]:
# Grab index 1 and everything after it
print(list1[1:])


['a', 'This is a list', 5.25]

In [18]:
# Grab the element from index position 1 to 3 (1 less than given)
print(list1[1:3])


['a', 'This is a list']

In [20]:
# Grab elements upto 3rd item
print(list1[:3])


[1, 'a', 'This is a list']

In [10]:
# Grab the last item in the list
print(list1[-1])


5.25

In [25]:
print(list1[-1:])


[5.25]

In [26]:
# Third parameter is the jump parameter
list2 = ['a','b','c','d','e','f','g']
list2[1:4:2]


Out[26]:
['b', 'd']

In [27]:
# Concatenate Elements
list2 + ["added"]


Out[27]:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'added']

In [28]:
# unless reassigned the added item is not permanently added
list2


Out[28]:
['a', 'b', 'c', 'd', 'e', 'f', 'g']

In [29]:
list2 = list2 + ["added permanently"]
list2


Out[29]:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'added permanently']

In [30]:
list3 = list2 * 2
list3


Out[30]:
['a',
 'b',
 'c',
 'd',
 'e',
 'f',
 'g',
 'added permanently',
 'a',
 'b',
 'c',
 'd',
 'e',
 'f',
 'g',
 'added permanently']

List Methods


In [31]:
list4 = ['a','b','d','e']
list4.insert(2,'c')
list4


Out[31]:
['a', 'b', 'c', 'd', 'e']

In [33]:
list4.append(['f','g'])
list4


Out[33]:
['a', 'b', 'c', 'd', 'e', ['f', 'g']]

In [34]:
popped_item = list4.pop()
popped_item


Out[34]:
['f', 'g']

In [35]:
print(list4)


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

In [36]:
# sort elements
list4.sort()
list4


Out[36]:
['a', 'b', 'c', 'd', 'e']

In [37]:
# reverse elements
list4.reverse()
list4


Out[37]:
['e', 'd', 'c', 'b', 'a']

In [38]:
list4.remove('a')
list4


Out[38]:
['e', 'd', 'c', 'b']

In [39]:
list5 = ['a','f']
list4.extend(list5)
list4


Out[39]:
['e', 'd', 'c', 'b', 'a', 'f']

In [40]:
del list4[2]
list4


Out[40]:
['e', 'd', 'b', 'a', 'f']

In [42]:
# count the items
list4.count('a')


Out[42]:
1

In [45]:
# check if item exists in a list
if 'a' in list4:
    print('found')


found

In [46]:
print(list4.index('a'))


3