Presentation is loading. Please wait.

Presentation is loading. Please wait.

PYTHON LISTS. What are lists? An ordered set of elements A variable with 0 or more things inside of it Examples myList = [8, 6, 7, 5, 3, 0, 9] strList.

Similar presentations


Presentation on theme: "PYTHON LISTS. What are lists? An ordered set of elements A variable with 0 or more things inside of it Examples myList = [8, 6, 7, 5, 3, 0, 9] strList."— Presentation transcript:

1 PYTHON LISTS

2 What are lists? An ordered set of elements A variable with 0 or more things inside of it Examples myList = [8, 6, 7, 5, 3, 0, 9] strList = [“this”, “is”, “a”, “list”, “of”, “words”] comboList = [3, “blah”, 42, 423]

3 Creating a list Brackets [ ] are your friend Examples: emptyList = [] print(emptyList) groceries = [“milk”, “eggs”, “yogurt”] print(groceries)

4 Elements and Indexing Each slot / thing in a list is called an “element” How many elements are in the list myList = [3, 5, 7, 8]? Each element has an “index” or location JUST LIKE IN STRINGS! In the myList above, 3 is found at the 0 th index 5 is at the 1 th index 7? 8?

5 Accessing elements Just like in strings Access individual elements using brackets Example: int_list=[202,10, 54, 23] print( int_list[1] + int_list[3] ) int_list[0] = 1 #changing an element print(int_list)

6 List length Use len() function to find out the size of a list Examples: myList = [] print(len(myList)) myList2 = [8, 6, 7, 5, 3, 0, 9] print(len(myList2))

7 List slicing Access a slice (sub-list) using ranges (just like w/ strings) Includes first element in range, excludes last in range Example: int_list=[202,10, 54, 23] print(int_list[0:1]) print(int_list[2:3]) print(int _list[0:0]) Omit values to get start or end of list int_list[:2] int_list[2:]

8 Adding to a list Example myList = [5, 6, 87, 9, 2, 4] print(myList) myList.append(99999) print(myList)

9 Deleting from a list Example myList = [5, 6, 87, 9, 2, 4] print(myList) del myList[2] print(myList)

10 Iterating through a list Use a loop to walk through a list Example myList = [4, 3, 2, 6, 7, 8] x = 0 while x < len(myList): print(myList[x]) x = x + 1

11 Looping through a list to do something useful What is the algorithm for summing up a list of numbers? total = 0 myList = [4, 3, 2, 6, 7, 8] x = 0 while x < len(myList): total = total + myList[x] x = x + 1 print(total)

12 Additional List Resources Complete library of list functions/methods http://docs.python.org/release/3.1.3/tutorial/datastructures.html


Download ppt "PYTHON LISTS. What are lists? An ordered set of elements A variable with 0 or more things inside of it Examples myList = [8, 6, 7, 5, 3, 0, 9] strList."

Similar presentations


Ads by Google