Lists (Advanced)
Python programmers love lists because they are extremely versatile and can be used to store any type of data.
Advanced Slicing
You can use a negative index to access a list from the back of the list:
fruits = ['apple', 'banana', 'orange', 'pear', 'strawberry']
fruits[-1] # 'strawberry'
You can also slice a list to get a sublist:
fruits[0:2] # ['apple', 'banana']
You can check if an element exists in
a list:
'apple' in fruits # True
'carrot' in fruits # False
You can also iterate through the elements of a list.
for fruit in fruits:
print(fruit)
Output: apple banana orange
List Methods
Python has many built-in functions for working with lists.
.append()
If you want to add one item to the end of a list, use the .append() function.
[1, 2, 3].append(4) # [1, 2, 3, 4]
.pop()
If you want to remove an item from a list at a specific index, use the .pop() function.
[1, 2, 3].pop(1) # [1, 3]
.remove()
If you want to remove an item from a list, use the .remove() function.
[1, 2, 3].remove(2) # [1, 3]
.sort()
If you want to sort a list in ascending order, use the .sort() function.
[3, 5, 2, 4, 1].sort() # [1, 2, 3, 4, 5]
You can also sort strings in alphabetical order by using the .sort() function.
['a', 'c', 'b'].sort() # ['a', 'b', 'c']