8Lists
If you were asked to list all your friends in Python, you might think to create a variable for each friend and assign their name to the variable. However, you wouldn't be able to work with all friend variables easily in a program as you would have to remember the variable name for each individual friend and apply changes one by one. Python enables you to group related items together into a list, which provides you with a better experience to manipulate the collection of items.
Create a List
A list is a collection of items that are ordered and can be changed. This means that each item in the list has a specific position, and if you'd like to change the items in the list, you can do so. You can also have duplicate items in a list.
Let's create a list that consists of hobbies! Start with a variable hobbies
and place each of your hobbies in the list as a string.
>>> hobbies = ['swimming', 'dancing', 'singing']
To print the list, use print
()
and pass in the hobbies
variable. Python prints the entire list in order surrounded by brackets.
>>> hobbies = ['swimming', 'dancing', 'singing']
>>> print(hobbies)
['swimming', 'dancing', 'singing']
Checkpoint
Get Bite-Size Python now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.