Topics: Statement and Looping List
Topics: Statement and Looping List
Example:
List=[]
print(List)
OUTPUT:
[]
>>>
Using strings
Example:
list=[“GeeksForGeeks”]
print("\n List with the use of String: ")
print(List)
Output:
Example:
Example:
Output:
Multi-Dimensional List:
[['Geeks', 'For'], ['Geeks']]
>>>
The use of Numbers
It having duplicate value.
Example:
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print("\n List with the use of Numbers: ")
print(List)
Ouput:
Example:
Output:
Output:
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
>>>
The + Operator concatenates list:
Example:
a=[1,2,3]
b=[4,5,6]
c=a + b
print(c)
Output:
[1, 2, 3, 4, 5, 6]
>>>
The * Operator is:
a=[0] * 4
print(a)
Output:
[0, 0, 0, 0]
>>>
The Slice Operator:
Example:
a=[‘1’,’2’,’3’,’4’,’5’,’6’,’7’]
print(a[1:3])
print(a[4:])
print(a[:3])
a[3:5]=[‘8’,’9’]
print(a)
Output:
['2', '3']
['5', '6', '7']
['1', '2', '3']
['1', '2', '3', '8', '9', '6', '7']
>>>
Python list method have three types:
Append
Extend
Short
Append:
◦ Add an element to the end of the list
Eg:
t=[‘a’,’b’,’c’,’d’]
t.append(‘e’)
print(t)
Output:
['a', 'b', 'c', 'd', 'e']
>>>
Extend:
Add all elements of a list to the another list
Example:
t1=[‘a’,’b’,’c’]
t2=[‘d’,’e’]
t1.extend(t2)
print(t1)
Output:
['a', 'b', 'c', 'd', 'e']
>>>
Sort:
Sort items in a list in ascending order.
Example:
a=[‘4’,’2’,’6’,’1’,’3’,’5’]
a.sort()
print(a)
Output:
['1', '2', '3', '4', '5', '6']
>>>
Delete Python:
It have three types.
Pop()
Del operator
Remove()
Pop():
Removes and returns an element at the given index
Example:
a=[‘c’,’s’,’e’,’d’]
x=a.pop(2)
Print(a)
print(x)
Output:
['c', 's', 'd']
e
>>>
Del Operator:
It delete a element.
Example:
a=[‘s’,’v’,’k’]
del a[2]
print(a)
Output:
['s', 'v']
>>>
Remove:
Removes an item from the list.
Example:
a=[‘s’,’v’,’k’]
a.remove(‘v’)
print(a)
Output:
['s', 'k']
>>>
Remove all:
To remove more than one element, use del with a slice index.
Example:
a=[‘1’,’2’,’3’,’4’,’5’,’6’]
del a[2:4]
print(a)
Output:
['1', '2', '5', '6']
>>>
Example:
nums=[3,12,54,34,77,18]
print (len(nums))
print (max(nums))
print (min(nums))
print (sum(nums))
print (sum(nums)/len(nums))
Output:
6
77
3
198
33.0
>>>
Python list and string:
To convert from a string to a list of
characters you can use list.
Example:
s=‘spam’
t=list(s)
print(t)
Output:
['s', 'p', 'a', 'm']
>>>
Python Split:
Want to break a string into words, can use the split
method.
Example:
a=‘print the letter’
t=a.spilt()
print(t)
print(t[2])
Output:
['print', 'the', 'letter']
the
>>>
Delimiter:
Python uses a hyphen as a delimiter.
Example:
s=‘spam-spam-spam’
delimiter=‘-’
print(s.split(delimiter))
Output:
['spam', 'spam', 'spam']
>>>