List Data Type in Python
Concept
List is a collection which is mutable, ordered and changeable. Allows duplicate members.
List are just like the arrays, declared in other languages. List can contain int, float, str, list, dict, set any data type.
Code Example
Example 1:
# empty list
>>> l = []
[]
Example 2:
>>> l = [10, 20.35, 'Hello']
[10, 20.35, 'Hello']
Example 3:
>>> l = [10, 20.35, 'Hello']
>>> len(l)
3
>>> l [1]
20.35
# append
>>> l.append("New")
[10, 20.35, 'Hello', 'New']
>> l [1: 3]
[20.35, 'Hello']
>>> l [-3, -1]
20.35, 'Hello']
>>> l [0] = 40
>>> l
[40, 20.35, 'Hello', 'New']
# reverse
>>> l.reverse()
>>> l
['New', 'Hello', 20.35, 40]
# extend
>>> l = ['New', 'Hello', 20.35, 10]
>>> l1 = ['a', 'b']
>>> l.extend(l1)
>>> l
['New', 'Hello', 20.35, 10, 'a', 'b']
# pop()
>>> l = ['New', 'Hello', 20.35, 10]
>>> l.pop()
10
# sort
>>> l = [5, 2, 1, 3, 4]
>>> l.sort()
>>> l
[1, 2, 3, 4, 5]
# copy
>>> l = [1, 2, 3, 4, 5]
>>> l1 = l.copy()
>>> l1
[1, 2, 3, 4, 5]
# Data with List
t = (1, 2)
d = {1: 'A', 2: 'B'}
l1 = [1, 2]
s = {1, 2}
l = [10, t, d, l1, s, 20]
Output:
[10, (1, 2), {1: 'A', 2: 'B'}, [1, 2], {1, 2}, 20]
Comments
Post a Comment