Python List

In Python, lists allow us to store a sequence of items in a single variable.


Create a Python List

We create a list by placing elements inside square brackets [], separated by commas. For example,

 # a list of three elements
ages = [19, 26, 29]
print(ages)

# Output: [19, 26, 29]

Here, the ages list has three items.

More on List Creation

In Python, lists can store data of different data types.

# a list containing strings and numbers
student = ['Jack', 32, 'Computer Science']
print(student)

# an empty list
empty_list = []
print(empty_list)
Using list() to Create Lists

We can use the built-in list() function to convert other iterables (strings, dictionaries, tuples, etc.) to a list.

x = "axz"

# convert to list
result = list(x)

print(result)  # ['a', 'x', 'z']

List Characteristics

Lists are:

  • Ordered - They maintain the order of elements.
  • Mutable - Items can be changed after creation.
  • Allow duplicates - They can contain duplicate values.

Access List Elements

Each element in a list is associated with a number, known as a index.

The index always starts from 0. The first element of a list is at index 0, the second element is at index 1, and so on.

Index of List Elements
Index of List Elements

Access Elements Using Index

We use index numbers to access list elements. For example,

languages = ['Python', 'Swift', 'C++']

# access the first element
print(languages[0])   # Python

# access the third element
print(languages[2])   # C++
Access List Elements
Access List Elements

More on Accessing List Elements

Negative Indexing in Python

Python also supports negative indexing. The index of the last element is -1, the second-last element is -2, and so on.

Python Negative Indexing
Python Negative Indexing

Negative indexing makes it easy to access list items from last.

Let's see an example,

languages = ['Python', 'Swift', 'C++']

# access item at index 0
print(languages[-1])   # C++

# access item at index 2
print(languages[-3])   # Python
Slicing of a List in Python

In Python, it is possible to access a section of items from the list using the slicing operator :. For example,

my_list = ['p', 'r', 'o', 'g', 'r', 'a', 'm']

# items from index 2 to index 4
print(my_list[2:5])

# items from index 5 to end
print(my_list[5:])

# items beginning to end
print(my_list[:])

Output

['o', 'g', 'r']
['a', 'm']
['p', 'r', 'o', 'g', 'r', 'a', 'm']

To learn more about slicing, visit Python program to slice lists.

Note: If the specified index does not exist in a list, Python throws the IndexError exception.


Add Elements to a Python List

We use the append() method to add an element to the end of a Python list. For example,

fruits = ['apple', 'banana', 'orange']
print('Original List:', fruits)

# using append method fruits.append('cherry')
print('Updated List:', fruits)

Output

Original List: ['apple', 'banana', 'orange']
Updated List: ['apple', 'banana', 'orange', 'cherry']
Add Elements at the Specified Index

The insert() method adds an element at the specified index. For example,

fruits = ['apple', 'banana', 'orange']
print("Original List:", fruits) 

# insert 'cherry' at index 2 fruits.insert(2, 'cherry')
print("Updated List:", fruits)

Output

Original List: ['apple', 'banana', 'orange']
Updated List: ['apple', 'banana', 'cherry', 'orange']
Add Elements to a List From Other Iterables

We use the extend() method to add elements to a list from other iterables. For example,

numbers = [1, 3, 5]
print('Numbers:', numbers)

even_numbers  = [2, 4, 6]

# adding elements of one list to another numbers.extend(even_numbers)
print('Updated Numbers:', numbers)

Output

Numbers: [1, 3, 5]
Updated Numbers: [1, 3, 5, 2, 4, 6]

Change List Items

We can change the items of a list by assigning new values using the = operator. For example,

colors = ['Red', 'Black', 'Green']
print('Original List:', colors)

# changing the third item to 'Blue' colors[2] = 'Blue'
print('Updated List:', colors)

Output

Original List: ['Red', 'Black', 'Green']
Updated List: ['Red', 'Black', 'Blue']

Here, we have replaced the element at index 2: 'Green' with 'Blue'.


Remove an Item From a List

We can remove an item from a list using the remove() method. For example,

numbers = [2,4,7,9]

# remove 4 from the list numbers.remove(4)
print(numbers) # Output: [2, 7, 9]
Remove One or More Elements of a List

The del statement removes one or more items from a list. For example,

names = ['John', 'Eva', 'Laura', 'Nick', 'Jack']

# deleting the second item
del names[1]
print(names)

# deleting items from index 1 to index 3 
del names[1: 4]
print(names) # Error! List doesn't exist.

Output

['John', 'Laura', 'Nick', 'Jack']
['John']

Note: We can also use the del statement to delete the entire list. For example,

names = ['John', 'Eva', 'Laura', 'Nick']

# deleting the entire list
del names

print(names)

Python List Length

We can use the built-in len() function to find the number of elements in a list. For example,

cars = ['BMW', 'Mercedes', 'Tesla']

print('Total Elements: ', len(cars))  
  
# Output: Total Elements:  3

Iterating Through a List

We can use a for loop to iterate over the elements of a list. For example,

fruits = ['apple', 'banana', 'orange']

# iterate through the list
for fruit in fruits:
    print(fruit)

Output

apple
banana
orange

Python List Methods

Python has many useful list methods that make it really easy to work with lists.

Method Description
append() Adds an item to the end of the list
extend() Adds items of lists and other iterables to the end of the list
insert() Inserts an item at the specified index
remove() Removes item present at the given index
pop() Returns and removes item present at the given index
clear() Removes all items from the list
index() Returns the index of the first matched item
count() Returns the count of the specified item in the list
sort() Sorts the list in ascending/descending order
reverse() Reverses the item of the list
copy() Returns the shallow copy of the list

More on Python Lists

List Comprehension in Python

List Comprehension is a concise and elegant way to create a list. For example,

# create a list with square values
numbers = [n**2 for n in range(1, 6)]
print(numbers)    

# Output: [1, 4, 9, 16, 25]

To learn more, visit Python List Comprehension.

Check if an Item Exists in the Python List

We use the in keyword to check if an item exists in the list. For example,

fruits = ['apple', 'cherry', 'banana']

print('orange' in fruits)    # False
print('cherry' in fruits)    # True

Here,

  • orange is not present in fruits, so, 'orange' in fruits evaluates to False.
  • cherry is present in fruits, so, 'cherry' in fruits evaluates to True.

Note: Lists are similar to arrays (or dynamic arrays) in other programming languages. When people refer to arrays in Python, they often mean lists, even though there is a numeric array type in Python.


Also Read

  • Python list()

Table of Contents

Challenge

Write a function to find the largest number in a list.

  • For input [1, 2, 9, 4, 5], the return value should be 9.

Video: Python Lists and Tuples

Previous Tutorial:
Python Numbers, Type Conversion and Mathematics
Next Tutorial:
Python Tuple
Did you find this article helpful?

哆哆女性网周易的全文seo需要培训吗美容养生怎么宣传罗姓的男孩起名字网站设计语言seo的效果重庆网站建设父亲姓李起名字周易取名好不好民宿客房起名河南周易协会会员名单网站搜索引擎优化的建议解释梦的含义我真是大神医客栈名字廊坊特产及特色美食精灵梦可宝单机破解版下载巴铁是巴基斯坦还是巴勒斯坦苏州企业网站制作公司口是心苗知道生辰八字如何起名周六股票交易八字起名算命网韩国护肤品哪个牌子好直言贾祸造梦西游四最新破解版周易生辰八字起名免费测名推广平台先进营销吧团队卓起名女孩名字制作微网站制作淀粉肠小王子日销售额涨超10倍罗斯否认插足凯特王妃婚姻不负春光新的一天从800个哈欠开始有个姐真把千机伞做出来了国产伟哥去年销售近13亿充个话费竟沦为间接洗钱工具重庆警方辟谣“男子杀人焚尸”男子给前妻转账 现任妻子起诉要回春分繁花正当时呼北高速交通事故已致14人死亡杨洋拄拐现身医院月嫂回应掌掴婴儿是在赶虫子男孩疑遭霸凌 家长讨说法被踢出群因自嘲式简历走红的教授更新简介网友建议重庆地铁不准乘客携带菜筐清明节放假3天调休1天郑州一火锅店爆改成麻辣烫店19岁小伙救下5人后溺亡 多方发声两大学生合买彩票中奖一人不认账张家界的山上“长”满了韩国人?单亲妈妈陷入热恋 14岁儿子报警#春分立蛋大挑战#青海通报栏杆断裂小学生跌落住进ICU代拍被何赛飞拿着魔杖追着打315晚会后胖东来又人满为患了当地回应沈阳致3死车祸车主疑毒驾武汉大学樱花即将进入盛花期张立群任西安交通大学校长为江西彩礼“减负”的“试婚人”网友洛杉矶偶遇贾玲倪萍分享减重40斤方法男孩8年未见母亲被告知被遗忘小米汽车超级工厂正式揭幕周杰伦一审败诉网易特朗普谈“凯特王妃P图照”考生莫言也上北大硕士复试名单了妈妈回应孩子在校撞护栏坠楼恒大被罚41.75亿到底怎么缴男子持台球杆殴打2名女店员被抓校方回应护栏损坏小学生课间坠楼外国人感慨凌晨的中国很安全火箭最近9战8胜1负王树国3次鞠躬告别西交大师生房客欠租失踪 房东直发愁萧美琴窜访捷克 外交部回应山西省委原副书记商黎光被逮捕阿根廷将发行1万与2万面值的纸币英国王室又一合照被质疑P图男子被猫抓伤后确诊“猫抓病”

哆哆女性网 XML地图 TXT地图 虚拟主机 SEO 网站制作 网站优化