Lists in Python
In this tutorial we are going to learn :
- What is Python List
- list () and len () methods
- Accessing Items
- List Unpacking
Â
Â
What is Python List
Â
- A list is a collection that is ordered and changeable.
- In Python, we use square brackets to create a list.
- We can store integer, strings, floats, etc. in our lists.
Â
Example :
As you can see we can store any type of data in our lists.
list_of_numbers = [1, 2, 3, 4, 5]
list_of_strings = ["James", "John", "Adam"]
matrix = [[1, 2], [3, 5], [7, 2]] # list inside of list
my_list = [1, "James", 2.1, 7]
print(list_of_numbers)
print(list_of_strings)
print(matrix)
print(my_list)

Â
- We can use * for storing the same type of data in our list.Â
- We can use + to combine lists.
Example :
number = [1] * 10 # instead of writing 10 times, we use * to do it
my_list = ["a", "b", "c", "d"]
combine = number + my_list
print(combine)

Â
Â
Â
list() and len() Methods
Â
- We can also use the list() function to create a list.
- To learn how many items our list has, we use the len() function.
Â
Example :
# using list() function
first_list = list(range(10)) # 0 to 10 but 10 is not included
second_list = list("Hello World")
# using len() function
numbers_of_item = len(second_list)
# printing
print(first_list)
print(second_list)
print(f"Numbers of item : {numbers_of_item}")

Â
Â
Â
Accessing Items
Â
You can access items by referring to the index number.
Example :
my_list = ["a", "b", "c", "d", 1, 2, 3]
# Accessing Items
print(my_list[0])
print(my_list[-1])
# List Slicing
print(my_list[:]) # Accessing all items
print(my_list[0:]) # Accessing all items
print(my_list[0:3]) # Accessing index 0 to index 3, ,index 3 is not incuded
print(my_list[:3]) # Accessing index 0 to index 3, index 3 is not included
print(my_list[1:5]) # Accessing index 1 to index 5, index 5 is not included

List Unpacking
- If we have a list with many items we can access some items using the list unpacking method.
- We use the * operator for list unpacking.
Example :
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
first, second, *rest_of = my_list
print(f" First : {first} \n Second : {second} \n Rest of : {rest_of}")
# Accessing first and last items
first, *rest_of, last = my_list
print(f"\n First item : {first} \n Second item : {last} \n Rest of : {rest_of}")

