Python Basics
- Introduction to Python
- Installing Python in Windows
- Python Values, Variables and Types
- Python Variable Names and Keywords
- Python Statements
- Python Operators and Expressions
- Take input from User in Python
- Python Comments
- Python Conditional Execution
- Python Functions
- Python Loops
- Python Strings
- Python Lists
- Python Dictionaries
Python Lists
Like a string, a list is a sequence of values. In a string, the values are characters; in a list, they can be any type. The values in list are called elements or sometimes items.
How to create a list?
There are several ways to create a new list; the simplest is to enclose the elements in square brackets ([ and ]):
This is an example of a list of five integers.
numbers=[10, 20, 30, 40, 50]
print(numbers)
Here is an empty list.
empty=[]
Below example is a list of three strings.
food=['Hot dog','Sandwich', 'Hamburger']
print(food)
You can also create a list with mixed datatypes
mixed_list = [1, "Python", 1.5]
print(mixed_list)
The following list contains a string, a float, an integer, and another list:
nested_list= ['Python', 2.0, 5, [10, 20]]
print(nested_list)
Try it Yourself
Lists are mutable
The syntax for accessing the elements of a list is the same as for accessing the characters of a string: the bracket operator. The expression inside the brackets specifies the index. Remember that the indices start at 0:
food=['Hot dog','Sandwich', 'Hamburger']
print(food[0])
print(food[1])
Unlike strings, lists are mutable because you can change the order of items in a list or reassign an item in a list. When the bracket operator appears on the left side of an assignment, it identifies the element of the list that will be assigned.
numbers = [10, 20]
numbers[0] = 100
numbers[1] = 200
print(numbers)
The in operator also works on lists.
food=['Hot dog','Sandwich', 'Hamburger']
print('Hot dog' in food)
print('French fries' in food)
Try it Yourself
How to access elements from a list?
You have already seen in the above example that we can use the index operator [] to access an item in a list. Index starts from 0. So, a list having 3 elements will have index from 0 to 2.
List Index
food=['Hot dog','Sandwich', 'Hamburger']
print(food[0])
print(food[1])
If you try to read or write an element that does not exist, you get an IndexError
print(food[3])
Negative indexing
If an index has a negative value, it counts backward from the end of the list.
food=['Hot dog','Sandwich', 'Hamburger']
print(food[-1])
print(food[-2])
Try it Yourself
Traversing a list
The most common way to traverse the elements of a list is with a for loop.
food=['Hot dog','Sandwich', 'Hamburger'] for i in food: print(i)
Try it Yourself
Above method works well if you only need to read the elements of the list. But if you want to write or update the elements, you need the indices. A common way to traverse the list is to combine the functions range and len:
food=['Hot dog','Sandwich', 'Hamburger'] for i in range(len(food)): print(food[i])
Try it Yourself
List operations
The + operator concatenates lists:
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c)
Similarly, the operator repeats a list a given number of times:
a=[0]*4
print(a)
b=[1,2,3]*3
print(b)
The first example repeats four times. The second example repeats the list three times.
Try it Yourself
How to slice lists in Python?
The slice operator also works on lists. You can access a range of items in a list by using the slicing operator (colon).
l = ['make','me', 'analyst']
# get elements 2nd to 3rd
print(l[1:3])
# get elements beginning to 2nd
print(l[:-1])
# get elements 2nd to end
print(l[1:])
# elements beginning to end
print(l[:])
Try it Yourself
Since lists are mutable, it is often useful to make a copy before performing operations
that fold, spindle, or mutilate lists.
A slice operator on the left side of an assignment can update multiple elements:
t = ['a', 'b', 'c', 'd', 'e', 'f']
t[1:3] = ['x', 'y']
print(t)
Try it Yourself
List methods
Python provides methods that operate on lists. For example, append adds a new element to the end of a list:
x = ['a', 'b', 'c']
x.append('d')
print(x)
extend takes a list as an argument and appends all of the elements:
x1 = ['a', 'b', 'c']
x2 = ['d', 'e']
x1.extend(x2)
print(x1)
This example leaves x2 unmodified.
sort arranges the elements of the list from low to high:
t = ['d', 'c', 'e', 'b', 'a']
t.sort()
print(t)
Most list methods are void; they modify the list and return None. If you accidentally write t = t.sort(), you will be disappointed with the result.
Try it Yourself
How to delete or remove elements from a list?
There are several ways to delete elements from a list. If you know the index of the element you want, you can use pop:
t = ['a', 'b', 'c']
x = t.pop(1)
print(t)
print(x)
del operator
pop modifies the list and returns the element that was removed. If you don’t provide an index, it deletes and returns the last element.
If you don’t need the removed value, you can use the del operator:
t = ['a', 'b', 'c']
del t[1]
print(t)
remove()
If you know the element you want to remove (but not the index), you can use remove:
t = ['a', 'b', 'c']
t.remove('b')
print(t)
The return value from remove is None. To remove more than one element, you can use del with a slice index:
t = ['a', 'b', 'c', 'd', 'e', 'f']
del t[1:5]
print(t)
As usual, the slice selects all the elements up to, but not including, the second index.
Try it Yourself
Lists and functions
There are a number of built-in functions that can be used on lists that allow you to quickly look through a list without writing your own loops:
nums = [3, 4, 5, 6, 7, 8]
print(len(nums))
print(max(nums))
print(min(nums))
print(sum(nums))
print(sum(nums)/len(nums))
The sum() function only works when the list elements are numbers. The other functions (max(), len(), etc.) work with lists of strings and other types that can be comparable.
Try it Yourself
You could rewrite an earlier program that computed the average of a list of numbers entered by the user using a list. First, the program to compute an average without a list:
total = 0 count = 0 while (True): inp = input('Enter a number: ') if inp == 'done': break value = float(inp) total = total + value count = count + 1 average = total / count print('Average:', average)
In this program, You have count and total variables to keep the number and running total of the user’s numbers as we repeatedly prompt the user for a number. You could simply remember each number as the user entered it and use built-in functions to compute the sum and count at the end.
numlist = list() while (True): inp = input('Enter a number: ') if inp == 'done': break value = float(inp) numlist.append(value) average = sum(numlist) / len(numlist) print('Average:', average)
We make an empty list before the loop starts, and then each time we have a number, we append it to the list. At the end of the program, we simply compute the sum of the numbers in the list and divide it by the count of the numbers in the list to come up with the average.
Lists and strings
A string is a sequence of characters and a list is a sequence of values, but a list of characters is not the same as a string. To convert from a string to a list of characters, you can use list:
l="Make Me Aanlyst"
t = list(l)
print(t)
The list function breaks a string into individual letters. If you want to break a string into words, you can use the split method:
s = 'Make Me Aanlyst'
t = s.split()
print(t)
Try it Yourself
Once you have used split to break the string into a list of words, you can use the index operator (square bracket) to look at a particular word in the list. You can call split with an optional argument called a delimiter that specifies which characters to use as word boundaries. The following example uses a hyphen.
s = 'make-me-analyst'
delimiter = '-'
s.split(delimiter)
join is the inverse of split. It takes a list of strings and concatenates the elements. join is a string method, so you have to invoke it on the delimiter and pass the list as a parameter:
t = ['Make', 'Me', 'Analyst']
delimiter = ' '
delimiter.join(t)
Try it Yourself
List arguments
When you pass a list to a function, the function gets a reference to the list. If the function modifies a list parameter, the caller sees the change. For example, delete_head removes the first element from a list:
def delete_head(t): del t[0]
Here’s how it is used:
letters = ['a', 'b', 'c'] delete_head(letters) print(letters)
The parameter t and the variable letters are aliases for the same object. It is important to distinguish between operations that modify lists and operations that create new lists. For example, the append method modifies a list, but the + operator creates a new list:
t1 = [1, 2] t2 = t1.append(3) print(t1) print(t2)
t3 = t1 + [3] print(t3) t2 is t3
Try it Yourself