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)
Print all the items in list ‘name_list’
for name in name_list:
print(name)
Print numbers from 1 to 5 on separate lines
for value in range(1, 6):
print(value)
Print every other value from 1 to 10 on separate lines
for value in range(1, 11, 2):
print(value)
Create a list of numbers from 1 to 20 and assign it to ‘numbers’
numbers = list(range(1, 21))
What is a list comprehension?
A list comprehension combines the for loop and the creation of new elements into one line, and automatically appends each new element
Create a list of squares for each number ranging from 1 to 10, and assign it to variable ‘squares’
squares = [value ** 2 for value in range(1, 11)]
What is slicing?
Slicing is the extraction of a part of a string, list, or tuple. It enables users to access the specific range of elements by mentioning their indices. (source: simplilearn.com)
Make a slice of the first 5 items in ‘name_list’ and assign it to ‘first_users’
first_users = name_list[0:5]
Make a slice of the last 5 items in ‘name_list’ and assign it to ‘last_users’
last_users = name_list[-5:]
Print the last 3 items in ‘name_list’ on separate lines
for name in name_list[-3:]:
print(name)
Make a copy of ‘name_list’ and call it ‘users’
users = name_list[:]
What is a tuple?
A tuple is a list that cannot be changes (is immutable)
Define a tuple named ‘length’ with only one element (120).
length = (120, ) #notice the trailing comma, which is mandatory
Get the last value in tuple ‘length’ and assign it to “closet”
closet = length[-1]
Can you modify the items of a tuple?
You can’t modify a tuple, but you can assign a new value to a variable that represents a tuple.