Python list

List is essentialPythondata structure.

Allows you to group multiple values together and refer to them using common names.

E.g:

dogs = ["Roger", "Syd"]

The list can contain different types of values:

items = ["Roger", 1, "Syd", True]

you can use itinoperator:

print("Roger" in items) # True

The list can also be defined as empty:

items = []

You can refer to the items in the list with a zero-based index:

items[0] # "Roger"
items[1] # 1
items[3] # True

Using the same notation, you can change the value stored at a specific index:

items[0] = "Roger"

You can also useindex()method:

items.index(0) # "Roger"
items.index(1) # 1

As with strings, using a negative index will search from the beginning:

items[-1] # True

You can also use slices to extract part of the list:

items[0:2] # ["Roger", 1]
items[2:] # ["Syd", True]

uselen()The global function is the same as the function we used to get the length of the string:

len(items) #4

You can add items to the list using the listappend()method:

items.append("Test")

Or extend() method:

items.extend(["Test"])

You can also use+=operator:

items += ["Test"]

# items is [‘Roger’, 1, ‘Syd’, True, ‘Test’]

prompt:extend()or+=Don't forget the square brackets. Do not doitems += "Test"oritems.extend("Test")Or Python will add 4 separate characters to the list, thus['Roger', 1, 'Syd', True, 'T', 'e', 's', 't']

useremove()method:

items.remove("Test")

You can add multiple elements using

items += ["Test1", "Test2"]

#or

items.extend([“Test1”, “Test2”])

These append items to the end of the list.

To add an item to the middle of the list, at a specific index, useinsert()method:

items.insert("Test", 1) # add "Test" at index 1

To add multiple items at a specific index, you need to use slices:

items[1:1] = ["Test1", "Test2"]

usesort()method:

items.sort()

Hint: sort() only works when the list contains comparable values. For example, a string and an integer cannot be compared, and an error similar to the following will occurTypeError: '<' not supported between instances of 'int' and 'str'If you try.

Thissort()The method first sorts uppercase letters, and then sorts lowercase letters. To solve this problem, use:

items.sort(key=str.lower)

instead.

Sorting will modify the contents of the original list. To avoid this, you can use

itemscopy = items[:]

Or usesorted()Global functions:

print(sorted(items, key=str.lower))

It will return a new sorted list instead of modifying the original list.


More python tutorials: