top of page

Python Lists: Storing Names, Numbers, and Even Other Lists

Updated: Apr 21

Python lists are one of the best data structures for storing different types of data.


Observe:

My name is Bob.

I live in New York.

I work for XYZ Corp.

My favourite game is hockey.


How can we represent such information in Python?


Using Lists in Python

Lists are one of the data types in Python. Others include dictionaries, tuples, and sets. Lists are denoted by square brackets: [].


Quick Links


#1: Creating a List in Python


This is how we can create an empty list in Python:

sentences = []

Here, sentences is the name of the list variable. We are initialising an empty list: sentences.


Filling the List

Let us fill this list:

sentences = [ 
	"My name is Bob.", 
	"I live in New York.", 
	"I work for XYZ Corp.",
	"My favourite game is hockey."
]

We simply put the given strings enclosed in double quotation marks and separated by commas (,).


Let us check our list:

print(sentences)

# You will get:
['My name is Bob.', 'I live in New York.', 'I work for XYZ Corp.', 'My favourite game is hockey.']

Try using this notebook: Click on Python (Pyodide). Use Ctrl + Enter in Windows or Shift + Return on Mac.




#2: Python List Items


Consider this list:

names = ["Pulkit", "Bob", "Alice"]

A list is an ordered collection of different items. You can get the list items by specifying their positions inside the list. We use square brackets to access list elements. We use 0, 1, 2 to access list elements from left to right and –1, -2 to start accessing elements from the end.


Use this syntax:

# names[index]

names is the list variable name.

index is an integer indicating the position of an item, starting from 0 in Python. It is written inside [].


For example:

names[0]

This will give you the first item of the names list: 'Pulkit'

names[1]

This will give you the second names item: 'Bob'

And so on...


So, index 0 in Python represents the first item.


Try this:

sentences[-1]

You will get: 'My favourite game is hockey.'–This is the last item in the sentences list.


So, -1 indicates the last item.

sentences[-2]

Output: 'I work for XYZ Corp.'–This is the second last item.


#3: Modifying Python List Items


List elements or items can be integers, floats, strings, or even dictionaries, tuples, sets, or other lists.

# Initialising a list
register = ["list elements separated by commas"]

We have just initialised a list called register. Its elements can be numbers, strings, or other lists separated by commas.


Changing List Items

In our sentences list, if you wish to change hockey to cricket, you can modify the list content like this:

# You can use this syntax:
# list[index] = "new content"
sentences[3] = "My favourite game is cricket."

You can now check the list:

sentences
# You will get:
['My name is Bob.',
 'I live in New York.',
 'I work for XYZ Corp.',
 'My favourite game is cricket.']

We can use the len function to determine the length of a list.

len(sentences)

4


Adding Items

Now, let us add a new item to this list: "My favourite food is Paneer Masala"

You can do this by using a method called append(). For methods, you need to use dot notation followed by the method name.

# sentences.append()

We simply pass what we want to append inside the parentheses.

sentences.append("My favourite food is Paneer Masala.")

This will add a new item to the end of the sentences list.


You can check your list:

sentences
# You will get:
['My name is Bob.',
 'I live in New York.', 
 'I work for XYZ Corp.',
 'My favourite game is cricket.',
 'My favourite food is Paneer Masala.'
]

 

Removing Items

Let us remove this new item:

sentences.pop()

This will remove the last item.


You can also remove an item by directly providing it to another method called remove():

sentences.remove('I work for XYZ Corp.')

This will remove the item 'I work for XYZ Corp.' from the list only for the first item it's occurring.


You can also delete list items by this:

del sentences[1] 

Or delete the entire list if it's no longer needed:

# If you run this code, your entire list will be deleted. That’s why we commented it out.
# del sentences

Try and run:

sentences

What do you think you'll get?


Errors with List 

IndexError: List is out of range.


Try:

sentences[5]

List Slicing

You can slice a list into different pieces by providing the indices as follows:

# list[start:end] 

# 'start' is the starting index, and 'end' is the ending index (not # included).

# list[start:] # from 'start' index to the end of the list
# list[:end_index] # from the start of the list till the given end # (not included) 

Try:

sentences[0:]
# It will give all the list elements from the start to list end.

sentences[1:2]
# It will give list elements starting from second position (index 1) and ending at it, as index 2 is not included.

sentences[:2]
# It will give all elements from the start position till the second element, as the third element (index 2) is not included.

Sorting Lists

Let us sort sentences:

sentences.sort()

This will do an alphabetical sort of list of items and this process can't be undone so be careful. To avoid this you can use another function: sorted.

sorted(sentences)

You can change the order by passing in the argument.

sentences.sort(reverse=True)
sentences.reverse() # flipping a list 

Indexing Strings

You can use list indexing or slicing to get characters from a string.

name = "Pulkit"
print(name[0])
# You will get: P

print(name[5])
# You will get: t

print(name[6])
# You will get: IndexError

New Element

Inserting a new element:

# sentences.insert(position, new_thing)

# To insert at the second position or index 1:
sentences.insert(1, "My name is Rocky.")

Copying a List

To copy a list, you can make a slice that includes the entire original list by omitting the first index and the second index ([:]). 

# new = sentences[:]

We just discussed a lot about lists and how to modify them. There is a lot more we can do with lists. For more details, you can check the official documentation here.


In the next post, we will learn how to automate our work by using lists.



References


Sources


Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating

Most Read

AI Nine O Subscription

Subscribe to AI Nine O for 90-second learning.

Venus will reply here...

Your question...

VenusMoon Logo

Promoting equitable education for all through the fruitful use of AI.

© 2024-25 by VenusMoon Education | Udyam Registration Number: UDYAM-MP-10-0030480

bottom of page