In this article, we will explain List in Python through examples.
Lists are used to store multiple items in a single variable. List items are indexed, the first item has index
, the second item has index
, etc. Also, a
list is ordered, which means that the items have a defined order, and changeable, meaning that we can change, add and remove items in a
list after it has been created.
2. Create a List and Access Its Elements
Lists are created using square brackets
. List items are indexed and you can access them by referring to the index number. The first item has an index of
0. Furthermore, we can use negative indexing (-1 refers to the last item, -2 refers to the second-last item, etc). You can specify a range of indexes by specifying where to start(included) and where to end(not included) the range. When specifying a range, the return value will be a new
list with the specified items. Also, this is how you can
slice a list.
myList = ["car", "banana", "UFO", "red", 666] print(myList) print(myList) print(myList[-1]) print(myList[2:4])
3. Add/Change List Elements
To add an item to the end of the list, use the
append() method, and to insert an item at a specified index, use the
insert() method. Also, to append elements from another list to the current list, use the
extend() method. Last but not least, we can change the value of a specific item, refer to the index number.pythonList.py
myList = ["car", "banana", "UFO", "red", 666] myList = 50 print(myList) myList.insert(2, "inserted") print(myList) myList.append(True) print(myList) tmpList = [60, False, "papaya"] print(tmpList) myList.extend(tmpList) print(myList)
4. Delete/Remove List Elements
remove() method removes the specified item. The
pop() method removes the specified index. If you do not specify the index, the
pop() method removes the last item. The
del keyword also removes the specified index. The
del keyword can also delete the list completely.pythonList.py
myList = ["car", "banana", "UFO", "red", 666] myList.insert(0, "banana") print(myList) myList.remove("banana") print(myList) myList.pop(1) print(myList) del myList
As we can see from the examples above, lists are a very useful and simple way to store data in a sequence. It is more akin to an array in other programming languages. More list methods can be found here.
6. Download Source Code
This was an example of how we can create, parse, modify and delete a
list in python.
You can download the full source code of this example here: List in Python
Last updated on Dec. 20th, 2021