Python-Lists
Python-Lists
Python
Table of Contents
01 02 03
Lists Accessing a list List Operations
Create a list Slicing Summary
04 05 06
01
Lists
Basics
Lists
★ A list is a data type that allows you to store various types data
in it.
★ List items are indexed, the first item has index [0], the second item
has index [1] etc.
Lists - Ordered
★ When we say that lists are ordered, it means that the items have a
defined order, and that order will not change.
★ add new items to a list, the new items will be placed at the end of
the list.
Lists - changeable
★ The list is changeable, meaning that we can change, add, and
remove items in a list after it has been created.
list_name[index]
Example
# prints 11 # prints 11
print(numbers[0])
print(numbers[0])
Accessing items in a
list
1. The index cannot be a float number.
■ # a list of numbers
■ numbers = [11, 22, 33, 100, 200, 300]
■ # error
■ print(numbers[1.0])
2. The index must be in range to avoid IndexError.
# a list of numbers
numbers = [11, 22, 33, 100, 200, 300]
# error
print(numbers[6])
Accessing items in a
list
3. Negative Index to access the list items from the end
# list of numbers
★ n_list = [1, 2, 3, 4, 5, 6, 7]
★ # Whole list
★ print(n_list[:])
05
List Operations
List Operations
★ Basic list operations used in Python programming are
★ extend() ★ concatenate(),
★ insert() ★ min() & max()
★ append() ★ count()
★ remove() ★ multiply()
★ pop() ★ sort()
★ Slice ★ index()
★ Reverse() ★ clear() etc.
★ The append() method is used to add
elements at the end of the list.
★ This method can only add a single
element at a time.
★ To add multiple elements, the append()
method can be used inside a loop.
append() - Syntax
list.append(elmnt)
append() - syntax
list.append(elmnt)
elmnt
fruits = ['apple', 'banana', 'cherry'] Required. An
fruits.append("orange") element of any type
print(fruits) (string, number,
object etc.)