Lists Flashcards
Element
Each value in a list is referred to as an element.
Lists Format
Lists are created using square brackets ‘[ ]’. The basic syntax to create a list is as follows: my_list = [element 1, element 2, element 3, …]
Empty List
You can create an empty list by using empty square brackets: empty_list = []
Accessing Elements - Accessing a Single Element:
- The elements in a list are numbered with integers starting from 0.
- Access an individual list element by using the list’s name, followed by the element’s index enclosed in square brackets.
ex.) data = [2.71, 3.14, 1.41, 1.62]
print(data[1]) #Prints 3.14
Negative Indexes
- Negative indexes will start from the end of the list.
- The index ‘-1’ refers to the last element in the list.
- The index ‘-2’ refers to the second last element in the list.
ex.) Courses = [‘History’, ‘Math’, ‘Physics’, ‘CompSci’]
print(courses[-2]) #prints Physics
Modifying Lists
Sorting Lists
Looping Values
Accessing Elements - Accessing Multiple Elements:
ex.) courses = [‘History’, ‘Math’, ‘Physics’, ‘CompSci’]
print(courses[0:2]) #prints History and Math
Adding Elements to List Methods
- Append method
- Insert method
- Extend Method
Append Method
Insert Method
Extend Method