Python Lists
Python Lists
Python Lists
Lecture 4
Lists
• Python has a great built-in list type named "list". List literals are
written within square brackets [ ]. Lists work similarly to strings -- use
the len() function and square brackets [ ] to access data, with the first
element at index 0.
• The "empty list" is just an empty pair of brackets [ ]. The '+' works to
append two lists, so [1, 2] + [3, 4] yields [1, 2, 3, 4] (this is just like +
with strings).
List Length
• To determine how many items a list has, use the len() function:
• When specifying a range, the return value will be a new list with the
specified items.
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango"]
print(thislist[2:5])
Add List Items
• To add an item to the end of the list, use the append() method:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
Insert Items
To insert a list item at a specified index, use the insert() method.
The insert() method inserts an item at the specified index:
Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
Extend List
• To append elements from another list to the current list, use the
extend() method.
• Remove "banana":