Python Lists

Python : Lists

A list is a collection of ordered and mutable elements, which can be of different types such as integers, floats, strings, etc. Lists are created using square brackets [] and the elements are separated by commas.

List Items - Data Types

List items are ordered, changeable, and allow duplicate values.

numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "orange"]
booleanList = [True, False, True]
mixedList = ["apple", 34, True, 40, "orange"]

The list() Constructor

list() constructor can be used to creating a new list.

list1 = list((1,2,3,4)) # note the double round-brackets
print(list1) # Output: [1, 2, 3, 4 ]

List Length

To determine Length of list we can use len() function.

["apple", "banana", "cherry"]

print(len(thislist)) # Output: 3

Modify List

You can modify list by assigning new value to a list item or different inbuild methods like append(), insert(), remove(), sort() etc.

numbers = [1, 2, 3, 4, 5]
numbers[1] = 6 # Output: [1, 6, 3, 4, 5]
numbers.append(6) # Output: [1, 6, 3, 4, 5, 6]
numbers.sort() # Output:  [1, 3, 4, 5, 6, 6]

Python Collections (Arrays)

There are four collection data types(Arrays) in the Python :

  1. List is a collection which is ordered and changeable. Allows duplicate members.
  2. Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
  3. Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.
  4. Dictionary is a collection which is ordered** and changeable. No duplicate members.

List Comprehensions in Python