Lists Flashcards

1
Q

List

A

A list is a sequential collection of elements of any types. Each element is
identified by an index.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Creat a list

A

• 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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

example of list

A
vocabulary = ["iteration", "selection", "control"] 
numbers = [17, 123] 
empty = [] 
mixed_list = ["hello", 2.0, 5*2, [10, 20]] 
new_list = [numbers, vocabulary]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

List slice

A
list = ['a', 'b', 'c', 'd', 'e', 'f'] 
print list[1:3] 
print list[:4] 
print list[3:] 
print list[:]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

List are mutable

A
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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Object reference

A

a = “banana”
b = “banana”
print a is b # print True if a and b refer to the same object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

List aliasing

A

Since variables refer to objects, if we assign one variable to another, both
variables refer to the same object. This is called list aliasing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

List cloning

A

a = [81, 82, 83]
b = a[:] # make a clone using slice operator
print a == b
print a is b

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Repetition and references

A
orig_list = [45, 76, 34, 55] 
new_list = [orig_list] * 3 

print new_list

orig_list[1] = 99
print new_list

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

List methods

A
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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly