Lists
Lists
Divya Bahirwani
• There are 4 built-in data types in
Python.
• They used to store collections of data
• All have different qualities and usage.
1.List
2.Tuple
3.Set
4.Dictionary
Lists
List items are ordered,
List items are mutable (elements can be changed in place)
List items allow duplicate values.
Index
Indexing in Python is a way to refer the individual items within an
iterable (an object in which you can traverse through all the different
elements or entities contained within the object) by its position. In
other words, you can directly access your elements of choice within
an iterable and do various operations depending on your needs.
>>> a = []
>>> a = [1,2,3]
>>> a = [‘a’, ‘b’, ‘c’]
>>> a = [1, 2.5, 40 , 18.9]
>>> mixlist = [“Orange” , 12 , “Q” , “fruits” , “A-10”]
Creating a list from existing sequence
Syntax:
L = list(<sequence>)
• L is the list name
• List is function name
• Sequence is existing sequence of string
• Example:
>>> str = “hello”
>>> list1 = list(str)
>>> print (list1)
['h', 'e', 'l', 'l', 'o']
Accessing elements in a list
Syntax
<list name> [<index>]
Example:
>>> marks = [45,47,48,40,41]
>>> total = sum(marks)
print (total)
221
10. count()
The count() method returns the number of times the specified
element appears in the list.
Syntax:
<listname>.count(<element to be counted>)
Example:
list1 = [2, 3, 45, 34, 54, 34, 67, 34, 22, 33, 34]
print(list1.count(34))
4
9. Removing an element
• pop method is used
• Using the pop method – Python displays the element that is deleted.
• Syntax
<listname>.pop(position)
Example:
>>> marks = [45,47,48,40,41]
>>> marks.pop(2)
48
Example:
>>> for m in marks:
>>> print (m)
45
47
48
40
41
11. Copying a list
• Use copy()
Example:
>>> m = marks.copy()
>>> print (m)
[45, 47, 48, 40, 41]
in and not in operator
Example:
>>> languages = [“Python”, “Java”, “C++”, “Ruby”]
>>> print(“C++” in languages)
True
>>> print(“Kotlin” in languages)
False
>>> print(“Kotlin” not in languages)
True