List_In_Python
List_In_Python
A list is a collection of items in Python that is ordered, changeable, and allows duplicate
elements.
Key Points:
o Lists are used to store multiple items in a single variable.
o They can hold different data types (e.g., numbers, strings, etc.).
Example:
my_list = [1, "hello", 3.14]
Features of Lists
Example
fruits = ["apple", "banana", "apple"]
Creating a List
Syntax:
Use square brackets [ ] to define a list. Items are separated by commas.
empty_list = []
numbers = [10, 20, 30]
mixed = [1, "apple", 3.5]
# Addition of Elements
List.append(1) [1, 2, 4]
List.append(2)
List.append(4)
print(List)
# Addition of Element at
# specific Position [ 1, 2, 3, 12, 4]
List.insert(3, 12)
print( List)
[‘Kabir’, 1,2,3,12,4]
List.insert(0, 'Kabir')
print(List)
print(List)
.append () : Elements can be added to the List by using built-in append() function. Only one
element at a time can be added to the list by using append() method.
insert() Method :append() method only works for addition of elements at the end of the List, for
addition of element at the desired position, insert() method is used.
extend() method: Other than append() and insert() methods, there's one more method for
Addition of elements, extend(), this method is used to add multiple elements at the same time at
the end of the list.
.remove ():removes one element at a time.
.pop() : used to remove and return an element from the set, but by default it removes only the last
element of the set, to remove an element from a specific position of the List, index of the element
is passed as an argument to the pop() method.
List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12]
List.remove(5)
print[List]
Output:
[1, 2, 3, 4, 6, 7, 8, 9, 10, 11,12]
List1=[12,13,14,15,16,17]
List1.pop(5)
print[List]
Output:
[12,13,14,15,16]
For Loop:
While Loop
i=0
while i < len(fruits):
print(fruits[i])
i += 1
TRY BY YOURSELF
1) Create a list in Python of children selected for science quiz with following names- Arjun,
Sonakshi, Vikram, Sandhya, Sonal, Isha, Kartik
○ Print the whole list
○ Delete the name “Vikram” from the list
○ Add the name “Jay” at the end
○ Remove the item which is at the second position.