Skip to content

Lists

Lists are one of the most important data structures in Python. You can do lots of cool and useful things with lists.

A list is a collection of objects. It can contain strings, integers, or any other data type, including other lists! The items in a list can be all the same data type, or they can be a mix of different data types.

Strings

We’ve already talked about strings, but it’s useful to talk about them alongside lists, because many of the same methods you can use for lists apply to strings as well. Each character (letter, number, space, or other symbol) in a string acts like an item in a list. For example, you can loop through a string or check whether a certain character is in it. (Remember that Python is case sensitive.)

Joining & Splitting

You can join() a list to turn it into a string.

You type your list in the parentheses after join. The " " tells Python what to put in between the strings it’s joining together—a space, in this case. Try changing the space to something else.

You can also split() a string into a list:

The split() function automatically uses spaces to break up a string. However, you can use other characters too. Try .split(", ") or .split("s")!

 

Indexing

Indexing is a useful way to access a certain item in a list. Each item in a list has an index (plural: indices), which is like a shortcut for getting to that item. The index starts at zero, so instead of counting 1, 2, 3…, we count 0, 1, 2….

len() gives the number of items in a list, or the number of characters in a string. It comes in handy for indexing! And i is a commonly used variable for an index value.

String indexing follows the same rules as list indexing.

Slicing

Slicing is kind of like indexing, except instead of selecting one item, it can select as many (in a row) as you want.

If you leave out the value after the colon (e.g. [10:]), it will slice from the specified index to the end. Similarly, the slice [:10] will slice from the beginning of the list up to (but not including) index location 10.

Skip to toolbar