DEV Community

Cover image for Lists in Python
Benjamin Thorpe
Benjamin Thorpe

Posted on

Lists in Python

Hello Everyone!!
Today I will be sharing what I learned about lists in Python.

What are lists?

List are one of the most used, most powerful, most easy and also most efficient data structure built in to Python.

Some languages also call it arrays.

Basic structure of a list

# make a list of names
names = ['john', 'jack', 'mary', 'jane']
Enter fullscreen mode Exit fullscreen mode

and it's done, you can mix any datatype in a list but it is not recommended.

Adding Items to the list

To add items to an existing list use the append() method

# taking our initial list
names = ['john', 'jack', 'mary', 'jane']
print(names)

# == output ==
# ['john', 'jack', 'mary', 'jane']

# now let's add something
names.append('jonas')
# printing the changed list with name that we add
print(names)

# == output ==
# ['john', 'jack', 'mary', 'jane', 'jonas']
Enter fullscreen mode Exit fullscreen mode

Removing Items from the list

There are different options used to remove items in a list:
some common ones are:

pop() - removes the last value in the list

# taking our initial list
names = ['john', 'jack', 'mary', 'jane', 'jonas']

# let's say we don't want the last value again.
names.pop()

# let's print our list again
print(names)

# == output ==
['john', 'jack', 'mary', 'jane']
Enter fullscreen mode Exit fullscreen mode

remove(value) - removes the value passed in the list

# taking our initial list
names = ['john', 'jack', 'mary', 'jane', 'jonas']

# this time we want to remove 'mary'
names.remove('mary')

# let's print our list again
print(names)

# == output ==
['john', 'jack', 'jane', 'jonas']
Enter fullscreen mode Exit fullscreen mode

remove(value) only removes the first value it finds, not all of it.

del - deletes a value based on the index

# taking our initial list
names = ['john', 'jack', 'mary', 'jane', 'jonas']

# this time we only want to remove the second item
# lets assume we don't know the value.
del names[1]

# let's print our list again
print(names)

# == output ==
['john', 'mary', 'jane', 'jonas']
Enter fullscreen mode Exit fullscreen mode

There are many more functions to use in the list:
some others are:

  • sort() - sorts the list
  • copy() - returns a copy of the current list
  • extend(another_list) - extends a list to the current one.(almost like append()) This article. explains in detail
  • clear() - clears everything in the list.

Here are some other references

Thanks for reading, leave a comment or a suggestion to more links or code snippets.

Top comments (0)