03.1 Lists Dictionaries and Tuples (Part1)
03.1 Lists Dictionaries and Tuples (Part1)
Because a list usually contains more than one element, it’s a good idea to make the
name of your list plural, such as letters, digits, or names.
Unlike String, Lists objects are mutable. A mutable object is an object whose state can
be modified after it is created.
CREATING LIST
In Python, square brackets ([]) indicate a list, and individual elements in the list are
separated by commas.
Here’s a simple example of a list that contains four student names:
If you ask Python to print a list, Python returns its representation of the list, including
the square brackets:
mahmood
USING STRING METHODS ON A STING ELEMENT IN A LIST
You can also use the string methods on any sting element in a list.
For example, you can format an element more neatly by using the title() method:
This example produces the same output as the preceding example except 'Mahmood'
is capitalized.
INDEX POSITIONS START AT 0, NOT 1
Python considers the first item in a list to be at position 0, not position 1.
For example, to access the third item in a list, you request the item at index 2.
The output is a simple sentence about the first name in the list:
Output:
rania
['mahmood', 'ahmad', 'abdullah']
REMOVING ELEMENTS FROM A LIST
3. Popping Items from any Position in a List:
You can use pop() to remove an item from any position in a list by including the index
of the item you want to remove in parentheses.
For example, you might want to remove the name from a list names:
Output:
['mahmood', 'abdullah', 'rania']
REMOVING ELEMENTS FROM A LIST
If you’re unsure whether to use the del statement or the pop() method, here’s a simple
way to decide:
when you want to delete an item from a list and not use that item in any way, use the del statement;
if you want to use an item as you remove it, use the pop() method.
The remove() method deletes only the first occurrence of the value you specify.
If there’s a possibility the value appears more than once in the list, you’ll need to use a loop to make
sure all occurrences of the value are removed.
CHANGING, ADDING, AND REMOVING ELEMENTS
EXERCISE 2