0% found this document useful (0 votes)
0 views24 pages

Python List

The document provides a comprehensive overview of Python lists, covering their creation, indexing, slicing, and methods for adding, removing, and modifying elements. It also discusses list comprehension, membership tests, and various operations such as summing and finding maximum values. Additionally, it includes examples of common list operations and methods available in Python.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views24 pages

Python List

The document provides a comprehensive overview of Python lists, covering their creation, indexing, slicing, and methods for adding, removing, and modifying elements. It also discusses list comprehension, membership tests, and various operations such as summing and finding maximum values. Additionally, it includes examples of common list operations and methods available in Python.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python List

Python offers a range of compound datatypes often referred to as sequences. List is one of the
most frequently used and very versatile datatype used in Python.

How to create a list?


In Python programming, a list is created by placing all the items (elements) inside a square
bracket [ ], separated by commas.

It can have any number of items and they may be of different types (integer, float, string etc.).

1. # empty list
2. my_list =[]
3.
4. # list of integers
5. my_list =[1,2,3]
6.
7. # list with mixed datatypes
8. my_list =[1,"Hello",3.4]

Also, a list can even have another list as an item. This is called nested list.

# nested list

my_list = ["mouse", [8, 4, 6], ['a']]

How to access elements from a list?


There are various ways in which we can access the elements of a list.

List Index

We can use the index operator [] to access an item in a list. Index starts from 0. So, a list
having 5 elements will have index from 0 to 4.
Trying to access an element other that this will raise an IndexError. The index must be an
integer. We can't use float or other types, this will result into TypeError.

Nested list are accessed using nested indexing.

1. my_list =['p','r','o','b','e']
2. # Output: p
3. print(my_list[0])
4.
5. # Output: o
6. print(my_list[2])
7.
8. # Output: e
9. print(my_list[4])
10.
11. # Error! Only integer can be used for indexing
12. # my_list[4.0]
13.
14. # Nested List
15. n_list =["Happy",[2,0,1,5]]
16.
17. # Nested indexing
18.
19. # Output: a
20. print(n_list[0][1])
21.
22. # Output: 5
23. print(n_list[1][3])

Negative indexing

Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2
to the second last item and so on.

1. my_list =['p','r','o','b','e']
2.
3. # Output: e
4. print(my_list[-1])
5.
6. # Output: p
7. print(my_list[-5])
How to slice lists in Python?
We can access a range of items in a list by using the slicing operator (colon).

1. my_list =['p','r','o','g','r','a','m','i','z']
2. # elements 3rd to 5th
3. print(my_list[2:5])
4.
5. # elements beginning to 4th
6. print(my_list[:-5])
7.
8. # elements 6th to end
9. print(my_list[5:])
10.
11. # elements beginning to end
12. print(my_list[:])
Run Code

Slicing can be best visualized by considering the index to be between the elements as shown
below. So if we want to access a range, we need two indices that will slice that portion from
the list.

How to change or add elements to a list?


List are mutable, meaning, their elements can be changed unlike string or tuple.

We can use assignment operator (=) to change an item or a range of items.

1. # mistake values
2. odd =[2,4,6,8]
3.
4. # change the 1st item
5. odd[0]=1
6.
7. # Output: [1, 4, 6, 8]
8. print(odd)
9.
10. # change 2nd to 4th items
11. odd[1:4]=[3,5,7]
12.
13. # Output: [1, 3, 5, 7]
14. print(odd)
We can add one item to a list using append() method or add several items
using extend() method.
1. odd =[1,3,5]
2.
3. [Link](7)
4.
5. # Output: [1, 3, 5, 7]
6. print(odd)
7.
8. [Link]([9,11,13])
9.
10. # Output: [1, 3, 5, 7, 9, 11, 13]
11. print(odd)

We can also use + operator to combine two lists. This is also called concatenation.

The * operator repeats a list for the given number of times.

1. odd =[1,3,5]
2.
3. # Output: [1, 3, 5, 9, 7, 5]
4. print(odd +[9,7,5])
5.
6. #Output: ["re", "re", "re"]
7. print(["re"]*3)
Furthermore, we can insert one item at a desired location by using the method insert() or
insert multiple items by squeezing it into an empty slice of a list.
1. odd =[1,9]
2. [Link](1,3)
3.
4. # Output: [1, 3, 9]
5. print(odd)
6.
7. odd[2:2]=[5,7]
8.
9. # Output: [1, 3, 5, 7, 9]
10. print(odd)

How to delete or remove elements from a list?


We can delete one or more items from a list using the keyword del. It can even delete the list
entirely.
1. my_list =['p','r','o','b','l','e','m']
2.
3. # delete one item
4. del my_list[2]
5.
6. # Output: ['p', 'r', 'b', 'l', 'e', 'm']
7. print(my_list)
8.
9. # delete multiple items
10. del my_list[1:5]
11.
12. # Output: ['p', 'm']
13. print(my_list)
14.
15. # delete entire list
16. del my_list
17.
18. # Error: List not defined
19. print(my_list)
We can use remove() method to remove the given item or pop() method to remove an item
at the given index.
The pop() method removes and returns the last item if index is not provided. This helps us
implement lists as stacks (first in, last out data structure).
We can also use the clear() method to empty a list.
1. my_list =['p','r','o','b','l','e','m']
2. my_list.remove('p')
3.
4. # Output: ['r', 'o', 'b', 'l', 'e', 'm']
5. print(my_list)
6.
7. # Output: 'o'
8. print(my_list.pop(1))
9.
10. # Output: ['r', 'b', 'l', 'e', 'm']
11. print(my_list)
12.
13. # Output: 'm'
14. print(my_list.pop())
15.
16. # Output: ['r', 'b', 'l', 'e']
17. print(my_list)
18.
19. my_list.clear()
20.
21. # Output: []
22. print(my_list)

Finally, we can also delete items in a list by assigning an empty list to a slice of elements.

1. >>> my_list =['p','r','o','b','l','e','m']


2. >>> my_list[2:3]=[]
3. >>> my_list
4. ['p','r','b','l','e','m']
5. >>> my_list[2:5]=[]
6. >>> my_list
7. ['p','r','m']

Python List Methods


Methods that are available with list object in Python programming are tabulated below.

They are accessed as [Link](). Some of the methods have already been used above.

Python List Methods

append() - Add an element to the end of the list

extend() - Add all elements of a list to the another list


insert() - Insert an item at the defined index

remove() - Removes an item from the list

pop() - Removes and returns an element at the given index

clear() - Removes all items from the list

index() - Returns the index of the first matched item

count() - Returns the count of number of items passed as an argument

sort() - Sort items in a list in ascending order

reverse() - Reverse the order of items in the list

copy() - Returns a shallow copy of the list

Some examples of Python list methods:

1. my_list =[3,8,1,6,0,8,4]
2.
3. # Output: 1
4. print(my_list.index(8))
5.
6. # Output: 2
7. print(my_list.count(8))
8.
9. my_list.sort()
10.
11. # Output: [0, 1, 3, 4, 6, 8, 8]
12. print(my_list)
13.
14. my_list.reverse()
15.
16. # Output: [8, 8, 6, 4, 3, 1, 0]
17. print(my_list)
List Comprehension: Elegant way to create new
List
List comprehension is an elegant and concise way to create a new list from an existing list in
Python.

List comprehension consists of an expression followed by for statement inside square


brackets.

Here is an example to make a list with each item being increasing power of 2.

1. pow2 =[2** x for x in range(10)]


2.
3. # Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
4. print(pow2)

This code is equivalent to

1. pow2 =[]
2. for x in range(10):
3. [Link](2** x)
A list comprehension can optionally contain more for or if statements. An
optional if statement can filter out items for the new list. Here are some examples.
1. >>> pow2 =[2** x for x in range(10)if x >5]
2. >>> pow2
3. [64,128,256,512]
4. >>> odd =[x for x in range(20)if x %2==1]
5. >>> odd
6. [1,3,5,7,9,11,13,15,17,19]
7. >>>[x+y for x in['Python ','C ']for y in['Language','Programming']]
8. ['Python Language','Python Programming','C Language','C
Programming']

Other List Operations in Python


List Membership Test
We can test if an item exists in a list or not, using the keyword in.
1. my_list =['p','r','o','b','l','e','m']
2.
3. # Output: True
4. print('p'in my_list)
5.
6. # Output: False
7. print('a'in my_list)
8.
9. # Output: True
10. print('c'notin my_list)
Iterating Through a List
Using a for loop we can iterate though each item in a list.
1. for fruit in['apple','banana','mango']:
2. print("I like",fruit)

Python List

Sum all the items in a list


defsum_list(items):
sum_numbers =0
for x in items:
sum_numbers += x
return sum_numbers
print(sum_list([1,2,-8]))

Multiplies all the items in a list


defmultiply_list(items):

tot =1

for x in items:

tot *= x

return tot

print(multiply_list([1,2,-8]))

Get the largest number from a list


defmax_num_in_list(list):

max=list[0]

for a inlist:

if a >max:

max= a

returnmax

print(max_num_in_list([1,2,-8,0]))
Get the smallest number from a list
defsmallest_num_in_list(list):
min=list[0]
for a inlist:
if a <min:
min= a
returnmin
print(smallest_num_in_list([1,2,-8,0]))

Count the number of strings where the


string length is 2 or more and the first and
last character are same from a given list of
strings
defmatch_words(words):
ctr =0

for word in words:


iflen(word)>1and word[0]== word[-1]:
ctr +=1
return ctr

print(match_words(['abc','xyz','aba','1221']))

Get a list, sorted in increasing order by the


last element in each tuple from a given list
of non-empty tuples
Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]

deflast(n):return n[-1]

defsort_list_last(tuples):
returnsorted(tuples, key=last)

print(sort_list_last([(2,5),(1,2),(4,4),(2,3),(2,1)]))

Sample Output:
[(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]
Remove duplicates from a list
a =[10,20,30,20,10,50,60,40,80,50,40]

dup_items =set()

uniq_items =[]

for x in a:

if x notin dup_items:

uniq_items.append(x)

dup_items.add(x)

print(dup_items)

Copy
Sample Output:
{40, 10, 80, 50, 20, 60, 30}

Check a list is empty or not


l =[]

ifnot l:

print("List is empty")

Copy
Sample Output:
List is empty

Clone or copy a list


original_list =[10,22,44,23,4]

new_list =list(original_list)

print(original_list)

print(new_list)

Takes two lists and returns True if they


have at least one common member
defcommon_data(list1, list2):
result =False
for x in list1:
for y in list2:
if x == y:
result =True
return result
print(common_data([1,2,3,4,5],[5,6,7,8,9]))
print(common_data([1,2,3,4,5],[6,7,8,9]))

Shuffle and print a specified list

from random import shuffle


color =['Red','Green','White','Black','Pink','Yellow']
shuffle(color)
print(color)

Generate all permutations of a list in


Python
import itertools
print(list([Link]([1,2,3])))

Difference between the two lists


list1 =[1,2,3,4]
list2 =[1,2]
print(list(set(list1)-set(list2)))

Access the index of a list


nums =[5,15,35,8,98]
for num_index, num_val inenumerate(nums):
print(num_index, num_val)

Convert a list of characters into a string


s =['a','b','c','d']
str1 =''.join(s)
print(str1)

Find the index of an item in a specified list


num =[10,30,4,-6]

print([Link](30))

Append a list to the second list


list1 =[1,2,3,0]
list2 =['Red','Green','Black']
final_list = list1 + list2
print(final_list)

Select an item randomly from a list


import random
color_list =['Red','Blue','Green','White','Black']
print([Link](color_list))
Check whether two lists are circularly
identical
list1 =[10,10,0,0,10]
list2 =[10,10,10,0,0]
list3 =[1,10,10,0,0]

print('Compare list1 and list2')


print(' '.join(map(str, list2))in' '.join(map(str, list1 *2)))
print('Compare list1 and list3')
print(' '.join(map(str, list3))in' '.join(map(str, list1 *2)))

Get unique values from a list


my_list =[10,20,30,40,20,50,60,40]
print("Original List : ",my_list)
my_set =set(my_list)
my_new_list =list(my_set)
print("List of unique numbers : ",my_new_list)

Original List : [10, 20, 30, 40, 20, 50, 60, 40]
List of unique numbers : [40, 10, 50, 20, 60, 30]

Get the frequency of the elements in a list


import collections

my_list =[10,10,10,10,20,20,20,20,40,40,50,50,30]

print("Original List : ",my_list)

ctr = [Link](my_list)

print("Frequency of the elements in the List : ",ctr)

Copy
Sample Output:
Original List : [10, 10, 10, 10, 20, 20, 20, 20, 40, 40, 50,
50, 30]
Frequency of the elements in the List : Counter({10: 4, 20:
4, 40: 2, 50: 2, 30: 1})
Find the second largest number in a list
defsecond_largest(numbers):
if(len(numbers)<2):
return
if((len(numbers)==2)and(numbers[0]== numbers[1])):
return
dup_items =set()
uniq_items =[]
for x in numbers:
if x notin dup_items:
uniq_items.append(x)
dup_items.add(x)
uniq_items.sort()
return uniq_items[-2]
print(second_largest([1,2,3,4,4]))
print(second_largest([1,1,1,0,0,0,2,-2,-2]))
print(second_largest([2,2]))
print(second_largest([1]))

Count the number of elements in a list


within a specified range
defcount_range_in_list(li,min,max):
ctr =0
for x in li:
ifmin<= x <=max:
ctr +=1
return ctr

list1 =[10,20,30,40,40,40,70,80,99]
print(count_range_in_list(list1,40,100))

list2 =['a','b','c','d','e','f']
print(count_range_in_list(list2,'a','e'))

Check whether a list contains a sublist


defis_Sublist(l, s):

sub_set =False

if s ==[]:

sub_set =True
elif s == l:

sub_set =True

eliflen(s)>len(l):

sub_set =False

else:

for i inrange(len(l)):

if l[i]== s[0]:

n =1

while(n <len(s))and(l[i+n]== s[n]):

n +=1

if n ==len(s):

sub_set =True

return sub_set

a =[2,4,3,5,7]

b =[4,3]

c =[3,7]

print(is_Sublist(a, b))

print(is_Sublist(a, c))

Copy
Sample Output:
True
False
Create a list by concatenating a given list
which range goes from 1 to n
Sample list : ['p', 'q']
n =5
Sample Output : ['p1', 'q1', 'p2', 'q2', 'p3', 'q3', 'p4', 'q4', 'p5', 'q5']
my_list =['p','q']

n =4

new_list =['{}{}'.format(x, y)for y inrange(1, n+1)for x in my_list]

print(new_list)

Find common items from two lists


color1 ="Red","Green","Orange","White"

color2 ="Black","Green","White","Pink"

print(set(color1)&set(color2))

Create multiple lists


obj ={}

for i inrange(1,21):

obj[str(i)]=[]

print(obj)

Sample Output:
{'1': [], '8': [], '14': [], '5': [], '17': [], '9': [], '2':
[], '7': [], '16': [], '19': [], '4': [], '18':
[], '13': [], '3': [], '15': [], '11': [], '20': [], '6': [],
'12': [], '10': []}

Split a list into different variables


color =[("Black","#000000","rgb(0, 0, 0)"),
("Red","#FF0000","rgb(255, 0, 0)"),
("Yellow","#FFFF00","rgb(255, 255, 0)")]
var1, var2, var3 = color
print(var1)
print(var2)
print(var3)

Generate groups of five consecutive


numbers in a list
l =[[5*i + j for j inrange(1,6)]for i inrange(5)]

print(l)

Copy
Sample Output:
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16,
17, 18, 19, 20], [21, 22, 23, 24, 25]]

Convert a pair of values into a sorted


unique array
L =[(1,2),(3,4),(1,2),(5,6),(7,8),(1,2),(3,4),(3,4),

(7,8),(9,10)]

print("Original List: ", L)

print("Sorted Unique Data:",sorted(set().union(*L)))

Copy
Sample Output:
Original List: [(1, 2), (3, 4), (1, 2), (5, 6), (7, 8), (1,
2), (3, 4), (3, 4), (7, 8), (9, 10)]
Sorted Unique Data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Insert an element before each element of a


list
color =['Red','Green','Black']
print("Original List: ",color)

color =[v for elt in color for v in('c', elt)]

print("Original List: ",color)

Copy
Sample Output:
Original List: ['Red', 'Green', 'Black']
Original List: ['c', 'Red', 'c', 'Green', 'c', 'Black']

Concatenate elements of a list


color =['red','green','orange']

print('-'.join(color))

print(''.join(color))

Copy
Sample Output:
red-green-orange
redgreenorange

Convert a string to a list


import ast

color ="['Red', 'Green', 'White']"

print(ast.literal_eval(color))

Copy
Sample Output:
['Red', 'Green', 'White']
Check if all items of a list is equal to a
given string
color1 =["green","orange","black","white"]

color2 =["green","green","green","green"]

print(all(c =='blue'for c in color1))

print(all(c =='green'for c in color2))

Copy
Sample Output:
False
True

Extend a list without append


x =[10,20,30]

y =[40,50,60]

x[:0]=y

print(x)

Copy
Sample Output:
[40, 50, 60, 10, 20, 30]

Remove duplicates from a list of lists


Sample list : [[10, 20], [40], [30, 56, 25], [10, 20], [33], [40]]
New List : [[10, 20], [30, 56, 25], [33], [40]]
import itertools

num =[[10,20],[40],[30,56,25],[10,20],[33],[40]]

print("Original List", num)


[Link]()

new_num =list(num for num,_ in [Link](num))

print("New List", new_num)

Copy
Sample Output:
Original List [[10, 20], [40], [30, 56, 25], [10, 20], [33],
[40]]
New List [[10, 20], [30, 56, 25], [33], [40]]

List: Cheat Sheet


Making a list:
colors = ['Red', 'Blue', 'Green', 'Black', 'White']
Accessing elements:
# Getting the first element
first_col = colors[0]
# Getting the second element
second_col = colors[1]
# Getting the last element
newest_col = colors[-1]
Modifying individual items:
# Changing an element
colors[0] = 'Yellow'
colors[-2] = 'Red'
Adding elements:
# Adding an element to the end of the list
[Link]('Orange')
# Starting with an empty list
colors = []
[Link]('Red')
[Link]('Blue')
[Link]('Green')
# Inserting elements at a particular position
[Link](0, 'Violet')
[Link](2, 'Purple')
Removing elements:
# Deleting an element by its position
del colors[-1]
# Removing an item by its value
[Link]('Green')
Popping elements:
# Pop the last item from a list
most_recent_col = [Link]()
print(most_recent_col)
# Pop the first item in a list
first_col = [Link](0)
print(first_col)
List length:
# Find the length of a list
num_colors = len(colors)
print("We have " + str(num_colors) + " colors.")
Sorting a list:
# Sorting a list permanently
[Link]()
# Sorting a list permanently in reverse alphabetical order
[Link](reverse=True)
# Sorting a list temporarily
print(sorted(colors))
print(sorted(colors, reverse=True))
# Reversing the order of a list
[Link]()
Looping through a list:
# Printing all items in a list
for col in colors:
print(col)
# Printing a message for each item, and a separate message
afterwards
for col in colors:
print("Welcome, " + col + "!")
print("Welcome, we're glad to see you all!")
The range() function:
# Printing the numbers 0 to 2000
for num in range(2001):
print(num)
# Printing the numbers 1 to 2000
for num in range(1, 2001):
print(num)
# Making a list of numbers from 1 to a million
nums = list(range(1, 1000001))
Simple statistics:
# Finding the minimum value in a list
nums = [23, 22, 44, 17, 77, 55, 1, 65, 82, 2]
num_min = min(nums)
# Finding the maximum value
nums = [23, 22, 44, 17, 77, 55, 1, 65, 82, 2]
num_max = max(nums)
# Finding the sum of all numbers
nums = [23, 22, 44, 17, 77, 55, 1, 65, 82, 2]
total_num = sum(nums)
Slicing a list:
# Getting the first three items
colors = ['Red', 'Blue', 'Green', 'Black', 'White']
first_three = colors [:3]
# Getting the middle three items
middle_three = colors[1:4]
# Getting the last three items
last_three = colors[-3:]
Copying a list:
# Making a copy of a list
colors = ['Red', 'Blue', 'Green', 'Black', 'White']
copy_of_colors = colors[:]
List of Comprehensions:
# Using a loop to generate a list of square numbers
squr = []
for x in range(1, 11):
sq = x**2
[Link](sq)
# Using a comprehension to generate a list of square numbers
squr = [x**2 for x in range(1, 11)]
# Using a loop to convert a list of names to upper case
colors = ['Red', 'Blue', 'Green', 'Black', 'White']
upper_cols = []
for cols in colors:
upper_cols.append([Link]())
# Using a comprehension to convert a list of names to upper
case
colors = ['Red', 'Blue', 'Green', 'Black', 'White']
upper_cols = [[Link]() for cols in colors]

You might also like