[go: up one dir, main page]

0% found this document useful (0 votes)
33 views18 pages

Lists

Lists are a versatile datatype that can contain elements of different types. Elements are accessed using indexes and can be updated, deleted, or appended. Lists support common operations like concatenation, membership testing, and iteration. Built-in functions like len(), max(), min(), sorted(), and enumerate() operate on lists. Common methods like append(), pop(), reverse(), and sort() modify lists in-place.

Uploaded by

Sravya Pendem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views18 pages

Lists

Lists are a versatile datatype that can contain elements of different types. Elements are accessed using indexes and can be updated, deleted, or appended. Lists support common operations like concatenation, membership testing, and iteration. Built-in functions like len(), max(), min(), sorted(), and enumerate() operate on lists. Common methods like append(), pop(), reverse(), and sort() modify lists in-place.

Uploaded by

Sravya Pendem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Lists

• The list is a most versatile data-type available


in Python which can be written as a list of
comma-separated values (items) between
square brackets.
• A list contains items that need not all have
the same type.
• List is a mutable object.
Creating a list
• Creating a list is as simple as putting different
comma-separated values between square
brackets.
• list1 = ['physics', 'chemistry', 1997, 2000];
• list2 = [1, 2, 3, 4, 5 ];
• list3 = ["a", "b", "c", "d"];
• Like string indices, list indices start at 0, and
lists can be sliced, concatenated and so on.
Accessing a 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.
• #!/usr/bin/python
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]
When the above code is executed, it produces the following result:
• 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.
• #!/usr/bin/python
list = ['physics', 'chemistry', 1997, 2000]
print "Value available at index 2 : " print list[2]
list[2] = 2001
print "New value at index 2 : " print list[2]
Delete List Elements

• To remove a list element, you can use either the del statement if
you know exactly which element(s) you are deleting or the
remove() method if you do not know.
• #!/usr/bin/python
list1 = ['physics', 'chemistry', 1997, 2000]
print list1
del list1[2]
print "After deleting value at index 2 : " print list1
When the above code is executed,
• ['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 : ['physics', 'chemistry', 2000]
Basic List Operations:
• Lists respond to the + and * operators much like
strings; they mean concatenation and repetition here
too, except
Python Expression
that the result
Results
is a new list, not
Description
a string.

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

For x in [1,2,3]: 123 Iteration


print x,
Indexing, Slicing, and Matrixes:
• Because lists are sequences, indexing and slicing work the
same way for lists as they do for strings.
• Assuming following input:
L = ['spam', 'Spam', 'SPAM!']

Python Expression Result Description


L[2] ‘SPAM!’ Index starts at 0
L[-2] ‘Spam’ Counting from right
L[1:] ‘Spam’ ‘SPAM!’ Slicing fetches sections
Cmp() function
• This function compares two lists.
• Algorithm:
1. Compare elements of both lists.
2. If elements are of same type, perform the compare and return the result.
3. If elements are different types, check to see if they are numbers.
a. If numbers, perform numeric coercion and compare.
b. If either element is number, then the other element is larger (numbers
are smallest)
c. types are sorted alphabetically by name.
4. If we reached the end of one lists, the longer list is larger.
5. If we exhaust both lists and share the same data, the result is a tie and 0 is
returned.
Sequence type functions
• len()
len() gives the total length of string.
>>>num_list=[1,2,3,4]
>>>len(num_list)
4
>>>len(num_list*2)
8
Max() and min()
• These functions returns the largest and smallest value from the list.
• If the list are of liked type objects, the functions would come in
handy.
• If mixed objects are used, then numbers are smallest and strings
are largest
Sorted() and reversed()
>>> s=[‘they’, ’stamp’, ’them’, ‘when’, “they’re”,
’small’]
>>> for t in reversed(s):
print t,
Small they’re when them stamp they
>>>sorted(s)
[‘small’, ‘stamp’, ‘them’, ‘they’, “they’re”, ‘when’]
Enumerate()
• enumerate(thing), where thing is either an
iterator or a sequence, returns a iterator that
will return (0, thing[0]), (1, thing[1]), (2,
thing[2]), and so forth.
Zip()
• This function returns a list of tuples, where the i-th tuple
contains the i-th element from each of the argument
sequences or iterables. The returned list is truncated in
length to the length of the shortest argument sequence.
Sum()
• sum(iterable[, start])
• Sums start and the items of an iterable from left to right and
returns the total.
• start defaults to 0.
• The iterable‘s items are normally numbers, and the start value
is not allowed to be a string.
>>>a=[6,4,5]
>>>sum(a)
15
>>>sum(a,5)
20
List() and tuple()
• These factory functions take iterables and make new lists and tuples out
of the data.
• These built-in functions are used to convert from one type to the other,
i.e., when you have tuple and you need to make a list and vice-versa.
List type built-in methods
• List.append(obj)
• List.count(obj)
• List.extend(seq)
• List.index(obj,i=0,j=len(list))
• List.insert(index,obj)
• List.pop(index=-1)
• List.remove(obj)
• List.reverse()
• List.sort(func=None,key=None,reverse=false)

You might also like