Lists in Python Flashcards
List syntax
Var=[‘smth’, ‘smth again’, ‘smth else’]
How to access elements in the List?
print=(list_name[index position])
[-index] - last items
Index position starts from 0 not 1
How to modify the value of the 1st item?
var[0]=”new value”
How to add element to the list?
var.append(‘new element’)
Add element to the end of the list
How to add element at any position to the list?
variable.insert(index, ‘element’)
How to remove item from the list?
del var[index]
In case if the index, position of the item is known
Which method we use when we want to use the value of the item after we remove it?
pop ()
Removes the last item in a list
How to remove an item from any position?
.pop()
.pop(index)
How to remove the item if index is not known, but only the value?
.remove(‘value’)
How to sort a list permanently?
(Alphabetically)
.sort()
sort(reverse=true)
How to sort list temporarily?
Maintain original order of the list, but present in a sorted order
Alphabetically
sorted() & reverse()
Function!
print(sorted(list_name))