Lists in Python
Lists in Python
A list is a collection which is ordered and changeable. In Python lists are written
with square brackets.
Example
Create a List:
Access Items
You access the list items by referring to the index number:
Example
Print the second item of the list:
Example
Print all items in the list, one by one:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
Example
Check if "apple" is present in the list:
List Length
To determine how many items a list has, use the len() method:
Example
Print the number of items in the list:
Add Items
To add an item to the end of the list, use the append() method:
Example
Using the append() method to append an item:
Example
Insert an item as the second position:
Remove Item
There are several methods to remove items from a list:
Example
The remove() method removes the specified item:
Example
Using the list() constructor to make a List:
List Methods
Python has a set of built-in methods that you can use on lists.
Method Description
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value