Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

10_Lists in Python

The document provides a comprehensive overview of Python lists, covering their characteristics, such as mutability and indexing, as well as how to access, update, and delete elements. It also discusses basic list operations, built-in functions, and methods for manipulating lists. Key examples illustrate the usage of these concepts in Python programming.

Uploaded by

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

10_Lists in Python

The document provides a comprehensive overview of Python lists, covering their characteristics, such as mutability and indexing, as well as how to access, update, and delete elements. It also discusses basic list operations, built-in functions, and methods for manipulating lists. Key examples illustrate the usage of these concepts in Python programming.

Uploaded by

Arif Ahmad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Lists in Python

Learning objective
• Python Lists
• Accessing Values in Lists
• Updating Lists
• Deleting List Elements
• Basic List Operations
• Built-in List Functions and Methods
Lists - Introduction
• The most versatile data type available in Python
• Written as a list of csv (items) between square brackets
• Items in a list need not be of the same type
• May contain Data Types like Integers, Strings, as well as Objects.
• Lists are mutable; they can be altered even after their creation.
• Lists are ordered and have a definite count.
• The elements in a list are indexed according to a definite
sequence and the indexing of a list is done with 0 being the first
index.
Lists – introduction
• Collection of Multiple Data.
• Holds Multiple Data types.
• Lists are Mutable.
• Store multiple data at same time.
• For example:

a = [1, 12.5, ‘a’, “python”]


list1 = ['physics', 'chemistry', 1997, 2000];
Accessing values in Lists
• To access values in lists, use the square brackets for slicing along
with the index or indices to obtain value available at that index.

a = ['Arif', 1, 12.5,"Trainer","Python", 'IITC']


print(a[0])
print(a[1])
print(a[3])
print(a[3:5])
print(a[3:])
Accessing values in Lists
L = [9,18,'Hi',12,"Hello",15.55,'Programming',100,125.5]
print(L[5])
print(L[1:5])
print(L[2:8])
print(L[2:9:3])
print(L[-1])
print(L[-5])

• How to take every nth element of a list?


• What if we want to have only every 2nd element of L?
• This is where the step parameter comes into play.
Accessing values in Lists
L = [9,18,'Hi',12,"Hello",15.55,'Programming',100,125.5]
print(L[0:9:3]) # Here ‘3’ is step parameter

• Now you also write the above code as


print(L[::3])

• Here both print(L[0:9:3]) and print(L[::3]) gives an output as


9, 12, 'Programming'
Updating Lists
• Lists in Python are mutable.

• Ater defining a list, it is possible to update the individual items or


multiple elements of lists by giving the slice on the left-hand side
of the assignment operator.

• You can also add to elements in a list with the append() method.
Updating Lists
z = [30, 17, 40, 2]
# Update the item at index 1 with the string “python"
print(z)
z[1] = "Python"
print(z) #Output->[30, 'Python', 40, 2]
z.append(100)
#Use of append method to add 100
print(z) #Output->[30, 'Python', 40, 2, 100]
Deleting List Elements
• To remove a list element, you can use either the del statement or
remove() method.

b = ['Python', 100, 'Programming', 2, 'is']


del b[1] # deleting element of 1st index
print(b) # ['Python', 'Programming', 2, 'is']
b.remove(2) # Removing the element ‘2’
print(b) # ['Python', 'Programming', 'is']
Basic List Operations
• Lists respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a new
list, not a string.

list1 = [10, 20, 30]


list2 = [40, 50]
result = list1 + list2
print(result)

# Repetition
list3 = [55] * 3
print(list3)
Built-in List Functions
• Python includes the following list functions:
• cmp(list1, list2) : Compares elements of both lists.
• Please note cmp() is notsupported in python 3.

• len(list): Gives the total length of the list.


• max(list):Returns item from the list with max value.
• min(list): Returns item from the list with min value.
cmp() function for comparison
• The cmp() function in Python 2 was used to compare two values
and return:

• -1 if the first value is less than the second,


• 0 if they are equal, and
• 1 if the first value is greater than the second.

• In Python 3, we can use custom function or by directly using


comparison operators.
cmp() function for comparison
def cmp(a, b):
return (a > b) - (a < b)

print(cmp(30, 50)) # Output: -1


print(cmp(50, 50)) # Output: 0
print(cmp(70, 50)) # Output: 1
list1 = ['Python', 100, 'Programming', 2, 'is']
print(len(list1))
list2 = [2,5,8,7,10,20,1]
print(max(list2))
list3 = [2,5,8,7,10,20,1]
print(max(list3))

list4 =["arif","vijay","said","nasser"]
print(len(list4))
print(min(list4))
print(max(list4))

nestedlist1=[[1,2],[5,7],[2,4]]
print(len(nestedlist1))
print(min(nestedlist1))
print(max(nestedlist1))
Built-in List Methods
• list.append(obj):
• Appends object obj to list
• list.count(obj):
• Returns count of how many times obj occurs in list
• list.index(obj):
• Returns the lowest index in list that obj appears
• list.insert(index, obj):
• Inserts object obj into list at offset index
• list.pop(obj=list[-1]) :
• Removes and returns last object or obj from list
Built-in List Methods
• list.remove(obj):
• Removes object obj from list
• list.reverse():
• Reverses objects of list in place
• list.sort([func]):
• Sorts objects of list, use compare func if given
• list.extend(sequence):
• Used to add all elements of a specified sequence (e.g., list, tuple, or set)
to the end of a list.
• This is different from append(), which adds the sequence itself as a single
element.
x = [1,2,3,1,4,5] x = [1,2,3,1,4,5]
print(x) x.reverse()
x.append(100) print(x)
print(x.count(1))
x.insert(2, 10) x.sort()
print(x) print(x)
x.remove(3) x.sort(reverse=True)
print(x) print(x)
print(x.index(1))
popped_element = x.pop() y=[10,20,15]
print(x) z=[30,40,50,60]
popped_element2 = x.pop(5) y.extend(z)
print(x) print(y)
# Extending list with a tuple
students = ["ahmed", "ali"]
more_students = ("yousuf", "salim")
students.extend(more_students)
print(students)

# Extending list with a string


letters = ["a", "b"]
additional_letters = "hello"
letters.extend(additional_letters)
print(letters)

# Extending list with a Set


some_more_students={"abdullah","waleed","waseem"}
students.extend(some_more_students)
print(students)
You must have learnt:
• Python Lists
• Accessing Values in Lists
• Updating Lists
• Deleting List Elements
• Basic List Operations
• Built-in List Functions and Methods

You might also like