Course Content
Introduction to Python
Introduction to Python
List Methods
Let's explore some basic techniques to work with lists:
len(t)
- returns the length of listt
, or in other words, the number of items it contains;list1 + list2
- combines two lists (both must be lists);t * n
- createsn
duplicates of listt
;t.append(x)
- adds a single itemx
to the end of listt
(this alters the original list);t.extend([x, y, ...])
- appends elementsx, y, ...
to the end of listt
(this also modifies the original list);t.copy()
- produces a duplicate of the listt
;t.count(x)
- tallies the number of occurrences ofx
in listt
.
As an example, let's enhance the list from our last discussion by adding more details, such as the capital city and the total number of states:
# Initial and new lists US_Info = ["USA", 9629091, 331002651] US_Info_new = ["Washington D.C.", 50] # Add new data using concatenation print(US_Info + US_Info_new) # Add new data using list method US_Info.extend(US_Info_new) print(US_Info)
Note
Keep in mind that the
.extend()
method needs an iterable object as its argument. In our case, we're using another list as the iterable.An iterable object in Python is an object that can be iterated over, meaning you can traverse through all its elements in a sequence, such as a list, tuple, or string.
Thanks for your feedback!