Python lists
Created By: chatGPT
In Python, a list is a collection that is ordered and mutable. This means you can change, add, and remove items from a list after it has been created. Lists are defined by having the values between square brackets
[]
. Here are some basic operations you can perform on lists:my_list = [1, 2, 3, 4, 5]
To access an element in a list, you can use its index. Remember that Python uses zero-based indexing, which means the first element is at index
0
.first_element = my_list[0] # This will be 1
You can also use negative indexing to access elements from the end of the list.
last_element = my_list[-1] # This will be 5
To add an element to the end of the list, you can use the
append()
method.my_list.append(6) # Now my_list becomes [1, 2, 3, 4, 5, 6]
To insert an element at a specific index, use the
insert()
method, which takes two arguments: the index and the object to insert.my_list.insert(0, 0) # Now my_list becomes [0, 1, 2, 3, 4, 5, 6]
To remove an element, you can use the
remove()
method, which removes the first occurrence of the specified value.my_list.remove(3) # Now my_list becomes [0, 1, 2, 4, 5, 6]
To delete an element at a specific index, you can use the
del
statement or the pop()
method. The pop()
method also returns the removed element.removed_element = my_list.pop(0) # Now my_list becomes [1, 2, 4, 5, 6] and removed_element will be 0
You can also slice lists to create a sublist. Use the syntax
[start:end]
to get elements from index start
to end-1
.sub_list = my_list[1:4] # This will give you [2, 4, 5]
To check if an item is in the list, use the
in
keyword.exists = 2 in my_list # This will return True
Lists can also be nested, meaning you can have a list of lists. This is useful for representing multi-dimensional data.
nested_list = [[1, 2, 3], [4, 5, 6]]
Finally, remember that lists can hold items of different data types, including strings, integers, and other lists.
mixed_list = [1, 'two', 3.0, [4, 5]]