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.
In [1]:
vowels = ['a','e','i','o','u']
print(vowels)
Lists can also hold multiple object types
In [2]:
list1 = [1,'a',"This is a list",5.25]
print(list1)
In [3]:
# Find the length of the list
len(list1)
Out[3]:
In [4]:
# Get the element using the index
print(list1[0])
print(list1[2])
In [17]:
# Grab index 1 and everything after it
print(list1[1:])
In [18]:
# Grab the element from index position 1 to 3 (1 less than given)
print(list1[1:3])
In [20]:
# Grab elements upto 3rd item
print(list1[:3])
In [10]:
# Grab the last item in the list
print(list1[-1])
In [25]:
print(list1[-1:])
In [26]:
# Third parameter is the jump parameter
list2 = ['a','b','c','d','e','f','g']
list2[1:4:2]
Out[26]:
In [27]:
# Concatenate Elements
list2 + ["added"]
Out[27]:
In [28]:
# unless reassigned the added item is not permanently added
list2
Out[28]:
In [29]:
list2 = list2 + ["added permanently"]
list2
Out[29]:
In [30]:
list3 = list2 * 2
list3
Out[30]:
In [31]:
list4 = ['a','b','d','e']
list4.insert(2,'c')
list4
Out[31]:
In [33]:
list4.append(['f','g'])
list4
Out[33]:
In [34]:
popped_item = list4.pop()
popped_item
Out[34]:
In [35]:
print(list4)
In [36]:
# sort elements
list4.sort()
list4
Out[36]:
In [37]:
# reverse elements
list4.reverse()
list4
Out[37]:
In [38]:
list4.remove('a')
list4
Out[38]:
In [39]:
list5 = ['a','f']
list4.extend(list5)
list4
Out[39]:
In [40]:
del list4[2]
list4
Out[40]:
In [42]:
# count the items
list4.count('a')
Out[42]:
In [45]:
# check if item exists in a list
if 'a' in list4:
print('found')
In [46]:
print(list4.index('a'))