Unit 2 List
Unit 2 List
Lists : Basic list operations, Replacing, inserting, removing an element; Searching and sorting a
list, Methods of list objects, using lists as Stacks and Queues, how efficient lists are when used
as stack or queue, List, and nested list Comprehensions
Dictionary - adding and removing keys, accessing, and replacing values, traversing
dictionaries.
UNIT 2: LIST
List
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store
collections of data, the other 3 are Tuple, Set, and Dictionary, all with
different qualities and usage.
Lists are created using square brackets:
Example
alpha = ["a", "b", "c"]
print(alpha)
List Items
List items are indexed, the first item has index [0], the
second item has index [1] etc.
Ordered
Note: There are some list methods that will change the order, but in
general: the order of the items will not change.
Changeable
Since lists are indexed, lists can have items with the same
value.
Example
print(alpha)
List Length
Example
alpha = ["a", "b", "c", "a", "c"]
print(type(alpha))
The list() Constructor
It is also possible to use the list() constructor when creating a new list.
Example
print(alpha)
Access List Items
Access Items
List items are indexed and you can access them by referring to the
index number:
alpha = ["a", "b", "c"]print(alpha[1])
Negative Indexing
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
Note : If you do not specify the index, the pop() method removes the
last item.
The del keyword also removes the specified index:
List1 = [10,20,30,40,50]
List2= [x+10 for x in List1]
print(List2)
Write a program to create a list with elements 1,2,3,4 and 5. Display even
elements of the list using list comprehension
Consider a list with five different Celsius values.
Convert all the Celsius values into Fahrenheit. Using
List Comprehension
Formula :
Fahrenheit = (9/5)*celsius + 32
Consider the list with mixed type of elements, such as