0% found this document useful (0 votes)
7 views

Lists

Uploaded by

223111
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Lists

Uploaded by

223111
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 23

List data structures

CS101
Introduction
• The most basic data structure in Python is the sequence.
• Each element of a sequence is assigned a number - its position or
index. The first index is zero, the second index is one, and so forth.
• The most common built-in data structures in python are lists ,
dictionaries, sets and tuples
• There are certain things you can do with all the sequence types.
• These operations include indexing, slicing, adding, multiplying, and
checking for membership.
• In addition, Python has built-in functions for finding the length of a
sequence and for finding its largest and smallest elements.
Python lists
• The list is the most versatile datatype available in Python, which can
be written as a list of comma-separated values (items) between
square brackets.
• Important thing about a list is that the items in a list need not be of
the same type.
Examples
• Creating a list is as simple as putting different comma-separated
values between square brackets.
• For example
• list1 = ['physics', 'chemistry', 1997, 2000]
• list2 = [1, 2, 3, 4, 5,6.78,0.9999,’D’]
• list3 = ["a", "b", "c", "d"];
• LIST4=[]
Accessing values of list
• To access values in lists, use the square brackets for slicing along with the index or
indices to obtain value available at that index.
• For example-
list1 = ['physics', 'chemistry', 1997, 2000]
0 1 2 3
list2 = [1, 2, 3, 4, 5, 6, 7 ]
0 12 3 4 5 6
print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])
Print(list1[1,-1])
• Output:
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
Updating lists
• You can update single or multiple elements of lists by giving the slice
on the left-hand side of the assignment operator, and you can add to
elements in a list with the append() method.
• For example-
list = ['physics', 'chemistry', 1997, 2000]
print ("Value available at index 2 : ", list[2])
list[2] = 2001
print ("New value available at index 2 : ", list[2])
• Output:
Value available at index 2 : 1997
Deleting elements from list
• To remove a list element:
• you can use either the del statement if you know exactly which element(s) you are
deleting.
• You can use the remove() method if you do not know exactly which items to delete.
• For example-
list = ['physics', 'chemistry', 1997, 2000]
print (list)
del list[2]
print ("After deleting value at index 2 : ", list)
• Output:
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 : ['physics', 'chemistry', 2000]
Operations on lists
Python Results Description

len([1, 2, 3]) 3 Length


[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition
3 in [1, 2, 3] True Membership
max([1,2,34,5,6,0]) 34 Maximum element

min([1,2,3,4,0,5,8]) 0 Minimum element


sum([1,2,3,4]) 10 Sum of elemets of a list
list(“HELLO”) [‘H’,’E’,’L’,’L’,’O’] Converts to iteratable list
sorted([3,4,1,2,0,8,7]) [0,1,2,3,4,7,8] Returns a sorted list
all([1,2,3,4]) True Returns true if all elements are true
all([0,1,2,3]) False
List Methods Num_list=[6,3,7,0,1,2,4,9]
method syntax Example Output

append() list.append(object) Num_list.append(10) [6,3,7,0,1,2,4,9,10]

count() list.count(object) Num_list.count(7) 1

index() list.index(count) Num_list.index(7) 2

insert() list.insert(index,object) Num_list.insert(3,100) [6,3,7,100,0,1,2,4,9]

pop() list.pop([index]) Num_list.pop() [6,3,7,0,1,2,4]


remove() list.remove(object) Num_list.index(7) [6,3,0,1,2,4,9]

reverse() list.reverse() Num_list.reverse() [9,4,2,1,0,7,3,6]

sort() list.sort() Num_list.sort() [0,1,2,3,4,6,7,9]

extend() list1.extend(list2) New_list=[3,5,7,9] [6,3,7,0,1,2,4,9,3,5,7,9]


Num_list.extend(New_list)
Indexing, Slicing
• Since lists are sequences, indexing and slicing work the same way for
lists as they do for strings.
• Assuming the following input
L=['C++'', 'Java', 'Python’]
Python Expression Results Description
L[2] 'Python' Offsets start at zero

L[-2] 'Java' Negative: count from the right

L[1:] ['Java', 'Python'] Slicing fetches sections


Looping in lists
• Program to print elements of list
Looping in lists
• Program to print index of elements of a list
Looping in lists
• Program to print both index of elements and the elements of a list
• Using enumerate()
List comprehensions
• List comprehensions provide a concise way to create lists.
• Common applications are to make new lists where each element is
the result of some operations applied to each member to create a
subsequence of those elements that satisfy a certain condition.
• For example, assume we want to create a list of squares, like:
squares = [i * i for i in range(10)]
Print( squares)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
List comprehensions
• A list comprehension consists of brackets containing an expression followed by a for
clause, then zero or more for or if clauses.
• The result will be a new list resulting from evaluating the expression in the context
of the for and if clauses which follow it.
• For example, this listcomp combines the elements of two lists if they are not equal:
1) [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
Output: [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
2) combs = []
for x in [1,2,3]:
for y in [3,1,4]:
if x != y:
combs.append((x, y))
print(combs)
• Output:[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
List comprehensions
• Every list comprehension in Python includes three elements:
1) expression is the member itself, a call to a method, or any other
valid expression that returns a value.
In the example above, the expression i * i is the square of the member
value.
2) member is the object or value in the list or iterable.
In the example above, the member value is i.
3) iterable is a list, set, sequence, generator, or any other object that
can return its elements one at a time. In the example above, the
iterable is range(10).
Syntax:
new_list = [expression for member in iterable (if conditional)]
examples
1) sentence = 'the rocket came back from mars'
vowels = [i for i in sentence if i in 'aeiou’]
Print(vowels)
• ['e', 'o', 'e', 'a', 'e', 'a', 'o', 'a’]
Other usage
• You can place the conditional at the end of the statement for simple
filtering, but what if you want to change a member value instead of
filtering it out?
• In this case, it’s useful to place the conditional near the beginning of
the expression:

• new_list = [expression (if conditional) for member in iterable]


example
original_prices = [1.25, -9.45, 10.22, 3.78, -5.92, 1.16]
prices = [i if i > 0 else 0 for i in original_prices]
Print(prices)
• [1.25, 0, 10.22, 3.78, 0, 1.16]
Other uses
• If you want to sum the squares of the first one-thousand integers,
then a list comprehension will solve this problem :

Print(sum([i * i for i in range(1000)]))


• 332833500
Nested comprehensions
• Comprehensions can be nested to create combinations of lists, dictionaries, and sets within a collection.
• The perfect data structure for storing this data could be a Python list comprehension nested within a
dictionary comprehension:
cities = ['Austin', 'Tacoma', 'Topeka', 'Sacramento', 'Charlotte']
temps = {city: [0 for _ in range(7)] for city in cities}
Print( temps)
• {
'Austin': [0, 0, 0, 0, 0, 0, 0],
'Tacoma': [0, 0, 0, 0, 0, 0, 0],
'Topeka': [0, 0, 0, 0, 0, 0, 0],
'Sacramento': [0, 0, 0, 0, 0, 0, 0],
'Charlotte': [0, 0, 0, 0, 0, 0, 0]
}
Nested lists
• Nested lists are a common way to create matrices, which are often used for mathematical
purposes
matrix = [[i for i in range(5)] for _ in range(6)]
Print( matrix)
• [
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]
]

You might also like