Data Types - List Flashcards
(12 cards)
What is the fastest and most memory-efficient way to generate a list of numbers
list(range(n))
fruits = [“apple”, “banana”, “cherry”]
Give 3 ways to remove “bananna” from this list
del fruits[1]
fruits.pop(1)
fruits.remove(“banana”)
a = [ ]
a += 15
What does the above return
TypeError
+= can be used to extend a String, List or Tuple, but 15 is an integer.
Further, for List only, .extend() gives the same result ( .extend() is specific to Lists)
a = [ ]
Give the best way to add the integer 15 to list “a” as an item
a.append(15)
a = [ ]
Extend List “a” by [15]
a += [15]
OR
a.extend([15])
Note: += is the same as .extend(), except += works with any iterable, .extend() only works with Lists
a = [1, 3, 4]
Add the Integer 2 to List “a” between 1 & 3
a.insert(1, 2)
Syntax: .insert(index, item)
Result: a = [1, 2, 3, 4]
for item in lst:
print(lst[item])
What does the above print
TypeError
This treats “item” like it’s an index, but it’s an item (in this case an item in “list”).
If you want to print the Item, it should be typed as below,
for item in list:
print(item)
lst = [7,2,9,4,7,1,8,5,3]
Find the total of these numbers
sum(lst)
lst = [1,2,3,4,5]
Give 2 ways of printing “5” from “lst”
print(lst[-1])
print(lst[4])
lst = [1,2,3,4,5]
Print “1” from “lst”
print(lst[0])
lst = [1,2,3,4,5]
what does each of the lines below print
lst[0]
lst[0:]
lst[0] = 0
lst[0:] = [1,2,3,4,5]
lst = [1,2,3,4,5]
what does each of the lines below print
lst[-1]
lst[-1:]
lst[-1] = 5 # Integer
lst[-1:] = [5] # List