PythonPlaza - Python & AI

Python

IntroductionVariablesIf-else
Strings Functions while-loop
For-LoopListSet
DictionaryTuple Try..Except
Class/ObjectInheritancePolymorphism
File Handling

List in Python:

In Python, the List is one of the most common data structures you’ll come across. It shows up in almost every Python project, whether you’re building a website, analyzing data, or making a game, whenever you need to keep track of a group of items. List refers to a collection of data items which are normally related. Instead of storing these data as seperate variables, we can store them as a list. For example, if you need to store grdes of 5 students, instead of storing them in studentGrade1, studentGrade2,studentGrade3, we can store them in a list.
A list has order, which means the items stay in the same sequence as you add them. It’s also changeable, so you can add, remove, or modify items even after the list is created. To make a list, just put your values inside square brackets [], and separate them with commas. You can use the append() method to add an item to the end, or insert() to put an item in a specific spot. If you want to add the item to the List at a specific position, just use the insert command. Let's see some code examples.

Create a List:



Code Example 1:
#Creates a list
listNames = ["John", "Joseph", "Jack"]
#Print
print(listNames)
#Output:
['John', 'Joseph', 'Jack']


Code Example 2A:
#Create List using append.
listStates = []
listStates.append["Arizona"]
listStates.append["Kansas"]
listStates.append["Nevada"]
#Print
print(listStates)
#Output:
['Arizona', 'Kansas', 'Nevada']

Code Example 2B:
#Create List using list().
listColor = list()
listColor.append["Green"]
listColor.append["Blue"]
listColor.append["Red"]
#Print
print(listColor)
#Output:
['Green', 'Blue', 'Red']

Code Example 3:
#Create list from tuple using list().
tuple1 = (10, 20, 30)
list_from_tuple = list(tuple1)
#Print
print(list_from_tuple)
#Output:
[10,20,30]


Code Example 4:
#Create list from another list.
list1 = ["Dublin","Fremont","Newark"]
list_from_another_list = list(list1)
#Print
print(list_from_another_list )
#Output:
 ["Dublin","Fremont","Newark"]


Code Example 5:
#insert the item at a given position.
listStates.insert(1,"Texas")
#Print
print(listStates)
#Output:
['Arizona', 'Texas', 'Utah', 'Nevada']


Simple Assignment (Creates a Reference):

When you assign one list to another, it does not create a new list. It creates a new reference to the same list object in memory. Python.



Code Example 6:
#Creates a list
list_A = [10, 20, 30]
#list_A refers to same object as list_B
list_B = list_A 

list_A.append(4)
#Print
print(list_A)
print(list_B)
#Output:
[10, 20, 30, 4]
[10, 20, 30, 4]

Update an item in List:

To update the items in the list, just assign a new value by refering to the index number.



Code Example 7:
#Creates a list
listCities = []
listCities.append("Chicago")
listCities.append("Houston")
listCities.append("Austin")
#Change the item "Dallas" to Phoenix,
listCities[1]="Phoenix"
#Print
print(listCities)
#Output:
['Chicago', 'Phoenix', 'Austin']

Remove an item in List:

To remove the item from the list, use the remove method. You can also remove one or more items in the list using del. The syntax is del listName[index of item to be deleted]. You can use pop to remove an item from the list and get its value.



Code Example 8:
#Creates a list
listCities = []
listCities.append("Fremont")
listCities.append("Stockton")
listCities.append("Turlock")
listCities.append("Newark")
#Remove an item using remove
listCities.remove("Stockton")
#Print
print(listCities)
#Output:   
['Fremont', 'Turlock', 'Newark']

Code Example 9:
#Remove item using del
del listCities[1]
#Print
print(listCities)
#Output:   
['Fremont', 'Newark']

Code Example 10:
#Remove items using del
del listCities[2:4]
#Print
print(listCities)
Output:   
['San Francisco', 'Fremont', 'Newark']

Length of List:

To find the length of the List, use the len method. Length of the list refers to the number of items in a list. The empty list will have 0 length. and the list with 10 items will have a length 10. If listA contains another list of 10 items, then the length of listA will be only 1.



Code Example 11:
#Creates a list
listColors = ['Green', 'Blue', 'Yellow']
#length of List
x=len(listColors)
#Print
print(listColors)
#Output:  
 3

Code Example 12:
#List containing another list
listA=['A', 'B', [1,2,3]]
print(len(listA))
#Print
print(listA)
#Output:  
 3

Loop through a List:

For loop can be used to loop through the List.



#Creates a list
listFruits = ["Banana", "Orange", "Apple"]
#Loop through the list
for x in listFruits:
  print(x)
#Print
print(listFruits)
#Output: 
Banana
Orange
Apple

Access items in a List:

You can use the index number to access item/items in the List.



#Creates a list
listFruits=["Banana","Orange","Apple","Grapes"]

#To access "Orange" in the List
x=listFruits[1]
#Print
print(x)
#Output:  
Orange

#To access "Grapes" in the List
x=listFruits[3]
#Print
print(x)
#Output:
Grapes

To access the last item of the List
x=listFruits[-1]
#Print
print(x)
#Output:   
Grapes

#To access the 2nd last item of the List
x=listFruits[-2]
#Print
print(x)
#Output:    
Apple

#To access the 2nd and 3rd items of the List

x=listFruits[1:3]
#Print
print(x)
#Output:   
['Orange', 'Apple']
Get all the fruits except Banana
x=listFruits[1:]
#Print
print(x)
#Output:    
['Orange', 'Apple', 'Grapes']

All items except last 2 items.
x=listFruits[:-2]
#Print
print(x)
#Output:    
['Banana', 'Orange']

Joining 2 Lists:

Use + operator to join 2 Lists..



#Creates a list
list1 = ["Honda", "Toyota", "Lexus"]
list2 = [1,2,3,4]

#Add 2 Lists with + operator.
list3=list1 + list2

#Print
print(list3)
#Output:   
['Honda', 'Toyota', 'Lexus', 1, 2, 3, 4]

Sorting the Lists

Lists can be sorted using the sort() method. To sort in descending order, pass the reverse = True argument. Use sorted() if you want a new sorted list to be created without changing the original list



#Creates a list
listCities = ["middletown", "chicago", "phoenix"]
#Sort
listCities.sort()
#Print
print(listCities)
#Output:   
['chicago', 'middletown', 'phoenix']

#To sort the the descending order.  
list1.sort(reverse=True)

#Print
print(list1)
#Output:        
['phoenix', 'middletown', 'chicago']

#Create a list
myList=[1,7,6,5]
sortedList=sorted(myList)
#Print
print(myList)
print(sortedList)
#Output: 
[1,7,6,5]
[1,5,6,7]

Copy the List

You can copy List into another List variable using copy() or list() method.



#Creates a list
listCars1 = ["Honda", "Toyota", "Lexus"]

#Copy to another List listCars2
listCars2 = listCars1.copy()

#Print
print(listCars2)

Output:          
['Honda', 'Toyota', 'Lexus']

Copy the list using list() method.
listCars2=list(listCars1)

#Print
print(listCars2)

Output:          
['Honda', 'Toyota', 'Lexus']

Extend

The extend() method in list is used to add all the items from another list, tuple, set, or string to the end of the current list.



#Creates a list
listCars = ["Honda"]

#Copy to another List listCars2
listCarsNew = ["Ford"]
listCars.extend(listCarsNew )
#Print
print(listCars)

Output:          
['Honda', 'Ford']