Lists Flashcards
List
A list is a sequential collection of elements of any types. Each element is
identified by an index.
Creat a list
• There are several ways to create a new list. The simplest is to enclose the
elements in square brackets ([ and ]).
• A list within another list is often call a sublist.
• Similar to strings, the len function returns the number of elements in the list.
example of list
vocabulary = ["iteration", "selection", "control"] numbers = [17, 123] empty = [] mixed_list = ["hello", 2.0, 5*2, [10, 20]] new_list = [numbers, vocabulary]
List slice
list = ['a', 'b', 'c', 'd', 'e', 'f'] print list[1:3] print list[:4] print list[3:] print list[:]
List are mutable
fruit = ["banana", "apple", "cherry"] print fruit fruit[0] = "pear" # Change one item using the index operator fruit[-1] = "orange" print fruit
list = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
list[1:3] = [‘x’, ‘y’] # Change two items using the slice operator
print list
- We can delete elements from a list by assigning the empty list to them.
- Or simply use the del statement.
Object reference
a = “banana”
b = “banana”
print a is b # print True if a and b refer to the same object
List aliasing
Since variables refer to objects, if we assign one variable to another, both
variables refer to the same object. This is called list aliasing.
List cloning
a = [81, 82, 83]
b = a[:] # make a clone using slice operator
print a == b
print a is b
Repetition and references
orig_list = [45, 76, 34, 55] new_list = [orig_list] * 3
print new_list
orig_list[1] = 99
print new_list
List methods
my_list = [] my_list.append(5) my_list.append(27) my_list.append(3) my_list.append(12) print my_list
my_list.insert(1, 12)
print my_list
print my_list.count(12)
print my_list.index(3)
print my_list.count(5)
my_list.reverse()
print my_list
my_list.sort()
print my_list
my_list.remove(5)
print my_list
last_item = my_list.pop()
print last_item
print my_list