Python Lists
Python List- Store Multiple Value Easily
Introduction
Until now, we stored single values only using variable. But what if you want to store marks of 5 subjects? Will you create 5 variables for that. No, Instead, Python gives us something powerful: Lists.
List allow us to store multiple values in a single variable.
What Is a List?
A list is a standard data type in python that can store a sequence of values separated by commas inside square brackets [ ]. It can store different data types. For example:
data= ["happy", 21, 85.6, True]
List can store strings, integers, floats, Boolean, even other lists. List are mutable i.e., you can change the values present in the list.
Creating Lists
To create a list you have to put number of expression, separated by commas inside the square brackets as depicted in the following:
L=[ ]
L=[values, ......]
To create empty list do as follows:
L=list() #It will generate empty list and the name of the list is L.
You can also create a list using built-in list type object to create lists from sequences as per the syntax given below:
L=list(<sequence>)
for example:
Code:
l1=list('hello')
print(l1)
Output:
['h', 'e', 'l', 'l', 'o']
You can also create a list from user input as follows:
Code:
l1=list(input("Enter list elements:"))
print(l1)
Output:
Enter list elements:543672
['5', '4', '3', '6', '7', '2']
Accessing List Elements(Indexing)
There are two types of indexing used in python positive and negative indexing. In positive indexing first element starts from 0 index and goes up till the last. where as in negative index, the indexing starts from the last element and goes up to first this indexing starts with -1, then -2, -3and so on.
Program to access the first element with the use of positive indexing :
For example:
Code:
fruits =["Apple", "Banana", "Grapes", "Mango", "Orange"]
print(fruits[0])
Program to access the first element with the use of negative indexing :
Code:
fruits =["Apple", "Banana", "Grapes", "Mango", "Orange"]
print(fruits[-5])
Modifying List Elements
List are mutable i.e., can be changed. To make a modification on the list we perform various operations like : appending, updating, deleting etc.
Appending Element To a List
Appending element means to add a single item at the end of the list. For this, python uses append() method. It can be done as per following format:
l1.append(Item)
Let's take above list of fruits example, suppose we want to append pineapple in the list then code will be:
fruits.append("Pineapple")
Inserting at Specific Position
To insert or update an element of the lit in place, you just have to assign new value to the element's index in list as per syntax:
fruits.insert(1, "Guava")
Deleting Element from a List
You can also remove items from list. In python, you can remove individual items or remove all the items identified by a slice. The syntax is given below:
del List [<index>]
del List [<start> :<stop>]
e.g.,
del fruits[2:4]
print(fruits)
Output:
["Apple", "Guava", "Pineapple"]
Or, You can use remove() method:
fruits.remove("Apple")
Or, you can use pop() method:
fruits.pop()
List Operations
Below are some of the common list operations.
Traversing a List
Traversing in a list means accessing and processing each element of it. The for loop makes it easy to traverse or loop over the items in a list. For example:
for fruit in fruits:
print(fruit)
This code will give name of each item in the list.
Output:
Apple
Banana
Grapes
Mango
Orange
Joining Lists
The concatenation operation +, when used with two list act as a join operator that helps to join two list. For example:
l1=[4,5,7,8]
l2=[23.56.78]
print(l1+l2)
Output:
[4,5,7,8,23,56,78]
Repeating or Replication List
We can use * operator to repeat the list as many times as we want. For example:
l1=[2,4,6]
print(l1*3)
The above expression will give you output as list value printed 3 times.
Output:
[2,4,6,2,4,6,2,4,6]
Slicing the List
Like a string, we can also use slicing in the list by using indexing. Example:
l1=[1,2,3,4,5,6,7,8,9]
print(l1[1:4])
Syntax:
seq=L[start:stop]
or
seq=L[start:stop:step]
list also support slice step that is we don't want to print continues element very to so be use step which skips the number of element that you have specify
print(l1[0:9:2])
Output:
[1,3,5,7,9]
Include every 2nd element, i.e., skip 1 element in between.
Finding Length of List
We use len() to find the length of the list. For example:
print(len(l1))
Output:
9
Real-Life Example: Student Marks
marks =[80,75,90,85]
total = sum(marks)
average = total / len(marks)
print("Total:", total)
print("Average:", average)
Practice Questions
- Create a list of 5 number and print them.
- Find the largest number in a list.
- Find sum of elements.
- Remove a specific element.
- Create a list of names and print them using loop.
Summary
- Lists store multiple values.
- Use [ ] to create list.
- Index starts from 0.
- Lists are mutable.
- Use append(), insert(), remove().
Comments
Post a Comment