Lists Flashcards
What is a list?
a collection of items in a particular order
Access the first element of the list ‘name_list’
name_list[0]
Access the last item in the list ‘name_list’
name_list[-1]
Change the third item of the list ‘name_list’
name_list[2] = ‘George’
Append a new item at the end of ‘name_list’
name_list.append(“Mary”)
Add a new item in the list ‘name_list’ in the fourth position
name_list.insert(3, “Francesco”)
When you use the .insert() method on a list, what happens to all the values that come after the inserted value?
They are all shifted one position to the right
Remove the 5th item from ‘name_list’
del name_list[4]
Remove the last item from ‘name_list’ and assign it to variable ‘user’
user = name_list.pop()
Remove first item from ‘name_list’ and assign it to variable ‘user’
user = name_list(0)
Remove user “George” from ‘name_list’ and assign it to variable ‘user’
user = name_list.remove(“George”)
Order the items of ‘name_list’ alphabetically and then reverse the order
name_list.sort()
name_list.sort(reverse=True)
Display the items in ‘name_list’ in alphabetical order without actually changing the order of the list
print(sorted(name_list))
Reverse the order of the items in list ‘name_list’
name_list.reverse()
Get the number of items in list ‘name_list’
len(name_list)