A list is a collection which is ordered and changeable that allows duplicate members. Lists are created using square brackets.
List
Sample Codeeven_numbers = [2,4,6,8,10]
print(even_numbers)
print(len(even_numbers)) # Number Of Items In List
duplicate_list = [2,4,6,8,10,2,4,6,8,10]
print(duplicate_list)
print(duplicate_list[1]) # Access List Item By Index Number
print(duplicate_list[2:5]) # Range Of Indexes
even_numbers[5] = 12 # Change Item Value By Index Number
print(even_numbers)
even_numbers.append(14) # Add Item To End
print(even_numbers)
even_numbers.insert(1, 2) # Insert Item Value At Index Number
print(even_numbers)
even_numbers.remove(2) # Remove Item Value
print(even_numbers)
even_numbers.pop(1) # Pop Item At Index Number
print(even_numbers)
del even_numbers.pop[1] # Remove Item At Index Number
print(even_numbers)
even_numbers.clear() # Remove All Items
print(even_numbers)
even_numbers.sort() # Sort All Items In Ascending Order
print(even_numbers)
even_numbers.reverse() # Sort All Items In Reverse Order
print(even_numbers)
copied_list = even_numbers.copy() # Make A Copy
print(copied_list)
list1 = [“John”, “Jake”]
list2 = even_numbers.copy()
list3 = list1 + list2 # Join Two Lists
list1.extend(list2) # Add Elements From One List
print(list1)
print(list3)
print(list1.count(“John”)) # Returns Number Of Times The Value “John” Appears
print(list1.index(“John”)) # Returns Index Of First Time The Value “John” Appears
Table : Common Functions For Manipulating Lists
Function | Description | Example |
---|---|---|
len() | Determine how many items | print(len(even_numbers) |
append() | Append items | even_numbers.append(12) |
insert() | Insert item at specified index | even_numbers.insert(1, 2) |
remove() | Remove specified item | even_numbers.remove(2) |
pop() | Pop the item at specified index | even_numbers.pop(1) |
del | Delete the item at specified index | del even_numbers.pop[1] |
clear() | Remove all values | even_numbers.clear() |
sort() | Sort in ascending order | even_numbers.sort() |
reverse() | Sort in reverse order | even_numbers.reverse() |
copy() | Make a copy | even_numbers.sort() |
extend() | Add elements from one list | list1.extend(list2) |
count() | Returns number of elements with specified value | list1.count(2) |
index() | Returns index of first element with specified value | list1.count(4) |