Python Lists

Updated: Aug 20, 2020


Python Lists


In the last article, we covered the string data type, here we are going to talk about Lists data type. Basically lists are -


  • Collection of items of different types.

  • Enclosed within a square bracket

  • Few of the operations are the same when we compare them to strings.

  • Unlike strings, lists are mutable


Lists can be thought of as the most general version of a sequence in Python. Unlike strings, they are mutable, meaning the elements inside a list can be changed!

Lists are constructed with brackets [] and commas separating every element in the list.

Let's go ahead and see how we can construct lists!



Example:


# Assign a list to an variable named my_list 
my_list = [1,2,3]
print(my_list)

We just created a list of integers, but lists can actually hold different object types.



Just like strings, the len() function will tell you how many items are in the sequence of the list.



Example:



my_list = ['A string',23,100.232,'o']
print(len(my_list))


Output:


4


Indexing and Slicing


Indexing and slicing work just like in strings. Let's make a new list to remind ourselves of how this works:



Example:


my_list=['one','two','three',4,5]

# Grab element at index 0
print(my_list[0])

Output:


one



Example:


# Grab index 1 and everything past it 
print(my_list[1:])

Output:


['two', 'three', 4, 5]


Example:


# Grab everything UP TO index 3 
print(my_list[:3])

Output:

 
 ['one', 'two', 'three']
 

We can also use + to concatenate lists, just like we did for strings.



Example:

  
print(my_list + ['new item'])
  

Output:


['one', 'two', 'three', 4, 5, 'new item']


Note: This doesn't actually change the original list!



Example:

 
print(my_list)
 

Output:


['one', 'two', 'three', 4, 5]


You would have to reassign the list to make the change permanent.


Example:


# Reassign 
my_list = my_list + ['add new item permanently']
print(my_list)

Output:


['one', 'two', 'three', 4, 5, 'add new item permanently']
 

We can also use the * for a duplication method similar to strings:


Example:


# Make the list double 
print(my_list * 2)

Output:


 ['one',
 'two',
 'three',
 4,
 5,
 'add new item permanently',
 'one',
 'two',
 'three',
 4,
 5,
 'add new item permanently']
 

Example:


# Again doubling is not permanent
print(my_list)

Output:


['one', 'two', 'three', 4, 5, 'add new item permanently']


Basic List Methods

If yo