Python: Adding To and Changing Lists

  1. Introduction to Python
  2. Python: Choosing a Text Editor or IDE
  3. Python: Hello World
  4. Python: Variables, Strings and Numbers
  5. Python: Variable Naming
  6. Python: Math, Familiar
  7. Python: Math, Less Familiar
  8. Python: Mathematical Order of Operations
  9. Python: Introducing PEP 8
  10. Python: Text Concatenation
  11. Python: if Statements and Comparison Operators
  12. Python: else and elif statements
  13. Python: Testing Multiple Conditions
  14. Python: Testing Sets of Conditions
  15. Python: Nested if Statements
  16. Python: Lists
  17. Python: Adding To and Changing Lists
  18. Python: Lists: Take a Slice, Delete Elements, Popping Elements
  19. Python: Tuples
  20. Python: for Loops
  21. Python: Nested for Loops
  22. Python: Capturing and Formatting User Input
  23. Python: Dictionaries
  24. Python: Functions
  25. Python: While Loops
  26. Python: Creating and Using Classes
  27. Python: Data Files
  28. Python: Modules
  29. Python: CSV Files
  30. Python: JSON Files
  31. Python: Errors and Exception Handling
  32. Python: Using Pexpect
  33. Python : Using Pexpect : ftpTestOffload.sh
  34. Python : Using Pexpect: ftpTest.py
  35. Python: DCL Conversion to Python

Go to Chapter 16 of A Smarter Way.

Return to our lists page:
http://introtopython.org/lists_tuples.html#Common-List-Operations

Change an item in a list:

friends = ['bill', 'jeff', 'jim']

friends[0] = 'fred'
print(friends)

Add an item to a list:

friends.append("joel")
# Note that we use parens, not brackets!
# That's because this is a function.
print(friends)

Find the index of an element:

print(friends.index("joel"))

Is an item in a list?

print('joel' in friends)
print('fanny' in friends)

If an item isn’t in the list, in the example above, of course nothing prints.

The Critical Difference Between sorted( ) and sort( )

See http://introtopython.org/lists_tuples.html#Finding-the-length-of-a-list
…and once again, scroll up because the page TOC is faulty.

sort( ) actually reorders the values in the list. The list, in other words, is changed.

sorted( ) does NOT change the list, it just returns a sorted version of the list to you.

Exercises

See http://www.asmarterwaytolearn.com/python/16.html

See http://introtopython.org/lists_tuples.html#Introducing-Lists

  1. Continue editing examples.py.
  2. Change the value of one item in your list.
  3. Find the index of one item by name.
  4. Perform a test to see if an item is in your list.